Oct 21, 2015

What is difference between UNION and UNION ALL in SQL Server

We use UNION and UNION ALL operator to combine multiple result set into one result set.
UNION operator is use to combine multiple result set into one result set but remove any duplicate rows. Basically UNION use to performing a DISTINCT operation across all columns in the result set. UNION operator has extra overhead of removing duplicate rows and sorting result.

UNION ALL operator use to combine multiple result set into one result set but it does not remove any duplicate result. Actually this is not remove duplicate rows so it is faster than UNION operator, if you want to combine multiple results and without duplicate records then use UNION.

Following some rules for using UNION/UNION ALL operator
·        Number of column should be same in the query's when you want to combine them.
·        Column should be of the same data type.
·        ORDER BY clause can be apply on overall result set not within each result set.
·        Column name of the final result set will be from the first query.



CREATE TABLE #TMP
(
      ID INT IDENTITY(1,1),
      NAME VARCHAR(100),
      [ADDRESS] VARCHAR(1000)
)
GO
INSERT INTO #TMP
  VALUES('Dilip','Gorakhpur'),
        ('Anil','Kushinagar')
GO


UNION


SELECT NAME,[ADDRESS] FROM #TMP
UNION
SELECT NAME,[ADDRESS] FROM #TMP


Result Set
NAME                          ADDRESS
---------------------------------------------------------------------------------
Anil                          Kushinagar
Dilip                         Gorakhpur

(2 row(s) affected)
Note: Above result set show UNION operator removes duplicates rows.
UNION ALL


SELECT NAME,[ADDRESS] FROM #TMP
UNION ALL
SELECT NAME,[ADDRESS] FROM #TMP


Result Set
NAME                           ADDRESS
---------------------------------------------------------------------------------------
Dilip                          Gorakhpur
Anil                           Kushinagar
Dilip                          Gorakhpur
Anil                           Kushinagar

(4 row(s) affected)

Note: UNION ALL returns all the rows including duplicates row.