Before continuing: This entry is part of the UNION guide. If you are new to the topic, start with UNION.
Examples
SELECT city FROM customers WHERE active = 1
UNION
SELECT city FROM customers WHERE email IS NULL;SELECT city FROM customers WHERE active = 1
UNION ALL
SELECT city FROM customers WHERE email IS NULL;The active customers live in London, Manchester, Bristol, Leeds, Birmingham and Edinburgh. The customers with no email are in Bristol, London and Edinburgh, cities that were already in the first result.
| Operation | Number of rows | Interpretation |
|---|---|---|
UNION | 6 | One row per distinct city. |
UNION ALL | 14 | Eleven rows from the first result and three from the second, repeats included. |
Differences and trade-offs
What a repeated row means
Imagine two lists of cities. If you want to know in which cities there is activity, a repeated city does not provide a new location and UNION fits. If each row represents a visit or an event, removing a repeat would destroy information and you need UNION ALL.
| Question | Choose | Reason |
|---|---|---|
| Need unique items? | UNION | It removes complete duplicate rows. |
| Does every occurrence count? | UNION ALL | It keeps the real number of occurrences. |
| Can the sets never overlap? | UNION ALL | There is no need to ask for a deduplication you don't need. |
| Not sure why duplicates appear? | Check first | A set operation does not fix a faulty model or JOIN. |
Requirements for the queries
Each query must return the same number of columns, and each position must hold compatible types. The result's column names usually come from the first query, so use clear aliases there.
SELECT city AS location
FROM customers
WHERE active = 1
UNION
SELECT city
FROM customers
WHERE email IS NULL
ORDER BY location;The ORDER BY applies to the combined result and is written once at the end. Without that clause, neither operation guarantees any particular order.
Performance without sacrificing meaning
UNION has to check which rows are identical in order to remove duplicates. UNION ALL avoids that deduplication, but that does not justify using it when the correct result requires uniqueness. Define the meaning first, then measure the real plan with the data and engine you use.