Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

What is difference between UNION and UNION ALL in SQL Server

$
0
0
We use UNION and UNION ALL operator to combine multiple result set into one result set.
UNIONoperator 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 ALLoperator 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.



CREATETABLE #TMP
(
      ID INTIDENTITY(1,1),
      NAME VARCHAR(100),
      [ADDRESS] VARCHAR(1000)
)
GO
INSERTINTO #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
UNIONALL
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.

Viewing all articles
Browse latest Browse all 265

Trending Articles