✏️ Explanatory Question
Level: Intermediate — A very common question that also tests your awareness of performance.
Both UNION and UNION ALL combine the results of two or more SELECT statements vertically (stacking rows). The difference is how they handle duplicate rows.
UNION ALL is faster because it skips the duplicate-elimination step. If you know there are no duplicates (or you want to keep them), always prefer UNION ALL.
| Feature | UNION | UNION ALL |
|---|---|---|
| Duplicates | Removed | Kept |
| Extra dedupe step | Yes (sort/compare) | No |
| Performance | Slower | Faster |
| Result size | Smaller / equal | Larger / equal |
| Use when | You need unique rows | Duplicates are fine/wanted |
Suppose two tables both contain the city 'Kolkata':
-- UNION: unique cities only
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
-- UNION ALL: all cities, duplicates preserved (faster)
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
-- Common use: combining monthly data where duplicates matter
SELECT amount FROM jan_sales
UNION ALL
SELECT amount FROM feb_sales; -- keep every transaction