UNION
joins two results and remove duplicates, while UNION ALL
does not remove duplicates.
UNION
also sort the final output.
W
The sort is used to eliminate the duplicates, and is implicit for DISTINCT
and UNION
queries (but not UNION ALL
) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns.
For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first:
SELECT foo, bar, 1 as ResultSet
FROM Foo
WHERE bar = 1
UNION
SELECT foo, bar, 2 as ResultSet
FROM Foo
WHERE bar = 3
UNION
SELECT foo, bar, 3 as ResultSet
FROM Foo
WHERE bar = 2
ORDER BY ResultSet