Comparison · Advanced SQL

UNION vs UNION ALL

UNION removes repeated rows; UNION ALL keeps every occurrence. Choose based on whether a repeat represents the same item or a separate fact.

Before continuing: This entry is part of the UNION guide. If you are new to the topic, start with UNION.

Examples

One copy of each city
SELECT city FROM customers WHERE active = 1
UNION
SELECT city FROM customers WHERE email IS NULL;
All occurrences
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.

Effect on the example result
OperationNumber of rowsInterpretation
UNION6One row per distinct city.
UNION ALL14Eleven 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.

Choosing between UNION and UNION ALL
QuestionChooseReason
Need unique items?UNIONIt removes complete duplicate rows.
Does every occurrence count?UNION ALLIt keeps the real number of occurrences.
Can the sets never overlap?UNION ALLThere is no need to ask for a deduplication you don't need.
Not sure why duplicates appear?Check firstA 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.

SQL
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.