SQL UNION vs UNION ALL
๐น What They Do
UNION and UNION ALL combine result sets produced by two or more SELECT statements. Both require matching column counts and compatible data types so the rows line up correctly.
๐น 1. UNION
- Combines rows and automatically removes duplicates.
- Performs an implicit
DISTINCT check.
- Runs slightly slower because duplicate elimination takes extra work.
SELECT city FROM customers
UNION
SELECT city FROM suppliers;
โ
Result: only the unique city names from both tables.
๐น 2. UNION ALL
- Combines rows and keeps duplicates intact.
- Skips the distinct comparison, so it is faster.
SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;
โ
Result: every city value, including duplicates.
๐น 3. Rules for Both
- Each
SELECT must return the same number of columns.
- Column data types must be compatible across the combined queries.
๐น Example Tables
| Customers |
| id | city |
| 1 | New York |
| 2 | London |
| Suppliers |
| id | city |
| 1 | London |
| 2 | Paris |
๐น UNION Result
New York
London
Paris
๐น UNION ALL Result
New York
London
London
Paris
๐น When to Use
- Use UNION when you only need unique values in the combined result.
- Use UNION ALL when duplicates carry meaningโsuch as counting total transactions or occurrences.