What is the difference between UNION
and UNION ALL
?
(From Microsoft SQL Server Book Online)
UNION [ALL]
Specifies that multiple result sets are to be combined and returned as a single result set.
ALL
Incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.
UNION
will take too long as a duplicate rows finding like DISTINCT
is applied on the results.
SELECT * FROM Table1
UNION
SELECT * FROM Table2
is equivalent of:
SELECT DISTINCT * FROM (
SELECT * FROM Table1
UNION ALL
SELECT * FROM Table2) DT
A side effect of applying
DISTINCT
over results is a sorting operation on results.
UNION ALL
results will be shown as arbitrary order on results But UNION
results will be shown as ORDER BY 1, 2, 3, ..., n (n = column number of Tables)
applied on results. You can see this side effect when you don't have any duplicate row.