How does UNION differ from UNION ALL? What are INTERSECT and EXCEPT?
UNION combines the results of two queries and removes duplicates, while UNION ALL keeps all rows and is therefore faster. INTERSECT returns rows present in both queries, and EXCEPT the rows of the first that are absent from the second; it is not symmetric, so verifying a migration needs both directions. Columns are matched by position, not by name, and two NULLs count as equal.
SQL · Subqueries, CTE, sets
After a migration the user count is the same. How to find who was not moved with one query?
A team is asked to verify a migration: the old system has three users, the new one has three too, but are they the same ones? Comparing by eye is dull, and JOIN and NOT IN give scattered results. Set operations compare whole results of queries: what exists only in one, what in both, what in total. This is the shortest way to answer "do two data sets match".
How it works and why. The operations combine the results of two queries by column position. The condition: the same number of columns and compatible types. Column names come from the first query. Rows are compared as a whole, and in this comparison two NULLs count as equal, unlike the ordinary =.
| Operation | What it returns | Duplicates |
|---|---|---|
| UNION | everything from both queries | removes |
| UNION ALL | everything from both queries | keeps |
| INTERSECT | what is in both | removes |
| EXCEPT | what is in the first and not in the second | removes |
The variants INTERSECT ALL and EXCEPT ALL in PostgreSQL compare taking the number of repeats into account. In Oracle EXCEPT is called MINUS, and MySQL supports INTERSECT and EXCEPT since 8.0.31. The example data: legacy_users has emails a, b, c, and users has emails a, c, d.
-- legacy_users: a, b, c; users: a, c, d (emails shortened to letters)
SELECT email FROM legacy_users
EXCEPT
SELECT email FROM users; -- b (did not migrate)
SELECT email FROM users
EXCEPT
SELECT email FROM legacy_users; -- d (appeared new)
SELECT email FROM legacy_users
INTERSECT
SELECT email FROM users; -- a, c
SELECT email FROM legacy_users
UNION
SELECT email FROM users; -- a, b, c, d (4)
SELECT email FROM legacy_users
UNION ALL
SELECT email FROM users; -- a, b, c, a, c, d (6)
What is being compared
| a |
| b |
| c |
| a |
| c |
| d |
The direction matters: EXCEPT is not symmetric. The first query tells who was lost (b), the second what extra appeared (d). A full migration check needs both. A coarser check is to compare row counts (COUNT(*)) and the sum of a control column. But only EXCEPT shows which records differ.
UNION against UNION ALL
Unique rows
A result without duplicates. For that the database sorts or hashes everything, so it is slower. a, b, c, d: 4 rows.
Everything as is
Duplicates stay, no extra work. a, b, c, a, c, d: 6 rows.
Limits and alternatives. Columns match by position, not by name. If the types are compatible there is no error, and the data is silently swapped:
-- the types are compatible, so there is no error, but the columns are swapped
SELECT first_name, last_name FROM staff
UNION ALL
SELECT last_name, first_name FROM contractors;
The precedence of the operations is surprising too: INTERSECT binds tighter than UNION and EXCEPT, and those run left to right. Parentheses make the intent explicit:
-- INTERSECT binds tighter: first B INTERSECT C, then A UNION the result
SELECT id FROM a
UNION
SELECT id FROM b
INTERSECT
SELECT id FROM c;
-- parentheses make the intent explicit
(SELECT id FROM a UNION SELECT id FROM b)
INTERSECT
SELECT id FROM c;
Two NULLs count as the same in set operations:
-- in set operations two NULLs count as the same
SELECT NULL
UNION
SELECT NULL; -- 1 row
Instead of EXCEPT people often write NOT EXISTS or LEFT JOIN … IS NULL. They compare by the key you name (for example only by id), while EXCEPT compares all selected columns at once. So EXCEPT suits a quick check of several columns and NOT EXISTS a check by key. UNION ALL is faster than UNION and fits when duplicates cannot occur or are wanted: for example when merging logs from several tables.
Typical mistakes.
UNIONwhere the count of all rows is needed: duplicates vanish and the count is understated.- A different column order in the two queries: the types match, there is no error, the data is swapped.
- One
EXCEPTin one direction and the conclusion "no differences": extra rows are not seen, both directions must be checked. - Mixing
UNIONwithINTERSECTwithout parentheses. ORDER BYbeforeUNION: only the result of the whole operation is sorted, and it is written at the end.
Check yourself
legacy_users has emails a, b, c and users has a, c, d. What does SELECT email FROM users EXCEPT SELECT email FROM legacy_users return, and why is the reverse query needed?
Answer
One row, d: a record that appeared in the new system and did not exist in the old one. The reverse query (legacy EXCEPT users) shows b, the one who was not moved. A migration check needs both directions.
Why can UNION give fewer rows than the sum of the rows of both queries, and what to do if you need all of them?
Answer
UNION removes fully identical rows, so the result can be shorter. If you need all rows from both queries, write UNION ALL: it removes nothing and is faster.