Union Vs Union All
Union Vs Union All
The UNION command is used to select related information from two tables, much like
the JOIN command. However, when using the UNION command all selected columns
need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL
selects all values.
Run following script to produce result for UNION and UNION ALL.
/* Create First Table */
DECLARE @Table1 TABLE (Col INT)
INSERT INTO @Table1
SELECT 1
INSERT INTO @Table1
SELECT 2
INSERT INTO @Table1
SELECT 3
INSERT INTO @Table1
SELECT 4
INSERT INTO @Table1
SELECT 5
The difference between Union and Union all is that Union all will not eliminate duplicate
rows, instead it just pulls all rows from all tables fitting your query specifics and
combines them into a table.
A UNION statement effectively does a SELECT DISTINCT on the results set. If you
know that all the records returned are unique from your union, use UNION ALL
instead, it gives faster results.
If you look at the resultset it is clear that UNION ALL gives result unsorted but in
UNION result are sorted. Let us see the query plan to see what really happens when this
operation are done.
From the plan it is very clear that in UNION clause there is an additional operation of
DISTINCT SORT takes place where as in case of UNION ALL there is no such
operation but simple concatenation happens. From our understanding of UNION and
UNION ALL this makes sense.
UNION RULES