What is difference between UNION and UNION ALL in SQL Server


We use UNION and UNION ALL operator to combine multiple results set into one result set.

UNION operator is used to combining multiple results set into one result set but removes any duplicate rows. Basically, UNION is used to performing a DISTINCT operation across all columns in the result set. UNION operator has the extra overhead of removing duplicate rows and sorting results.

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

Following some rules for using UNION/UNION ALL operator

1.  The number of the column should be the same in the query's when you want to combine them.
2.  The column should be of the same data type.
3.  ORDER BY clause can be applied to the overall result set not within each result set.

4.  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.

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...