What is the difference between UNION and UNION ALL, and how is UNION different from a JOIN?
EasyConceptSQL: Joins
Answer
UNION and UNION ALL stack the results of two queries on top of each other. UNION removes duplicate rows from the combined result, while UNION ALL keeps every row and is faster, because it skips the duplicate check (a sort or hash).
- Both queries must return the same number of columns with compatible types; the column names come from the first query.
- A JOIN combines tables side by side, adding columns by matching rows on a condition. A UNION combines results top to bottom, adding rows.
- Use
UNION ALLwhen duplicates are impossible or wanted, such as merging this year's and last year's orders.
Example: delhi(name) holds Asha and Ravi; mumbai(name) holds Ravi and Meera.
SELECT name FROM delhi
UNION
SELECT name FROM mumbai; -- Asha, Ravi, Meera (3 rows)
SELECT name FROM delhi
UNION ALL
SELECT name FROM mumbai; -- Asha, Ravi, Ravi, Meera (4 rows)