UNION, INTERSECT and EXCEPT
stacking results instead of joining them. and why UNION ALL is usually what you meant.
- address
- everything.joins.set_operations
- part
- part 3, joins and subqueries
- chapter
- chapter 10 of 11
- reading time
- 7 min
set operations stack two results that have the same columns: UNION keeps what's in either, INTERSECT what's in both, EXCEPT what's in the first and not the second. each removes duplicates, unless you add ALL, which keeps them and skips the work of removing them.
columns are matched by position, not by name.
the picture
you know the venn diagram from the first chapter of this part, the one that lies about joins? this is the chapter where it tells the truth. a join puts two tables side by side and makes rows wider. a set operation puts two results on top of each other: rows of the same shape, compared whole.
think of two shopping baskets. UNION ALL tips both into one big basket. UNION does that, then keeps one of each item. INTERSECT keeps the items both baskets have. EXCEPT takes Ada's basket and removes whatever Sean also has.
- 1SELECT item FROM ada UNION SELECT item FROM sean ORDER BY item NULLS LAST;
| item | m, ada | n, sean | out |
|---|---|---|---|
| atlas | 0 | 1 | 1 |
| kettle | 3 | 2 | 1 |
| whisk | 1 | 0 | 1 |
| null | 1 | 1 | 1 |
UNION: every distinct item from either basket, once. the two NULLs count as the same item.
look at the NULL row. in a join, NULL = NULL isn't true, so two NULLs never meet. set operations don't use =. they ask whether two rows are distinct, and two NULLs aren't, so UNION keeps one NULL and INTERSECT finds it in both baskets. it's the same rule GROUP BY and DISTINCT use (NULL and three-valued logic lists every place it applies).
the shop, by year
now real data. which customers ordered in 2025, which in 2026, and how do the two lists combine?
- 1SELECT count(*) AS customers FROM (
- 2 SELECT customer_id FROM orders WHERE ordered_at < timestamptz '2026-01-01 00:00+00'
- 3 UNION
- 4 SELECT customer_id FROM orders WHERE ordered_at >= timestamptz '2026-01-01 00:00+00'
- 5) AS x;
| customersint8 |
|---|
| 1962 |
UNION: customers who ordered in either year, each once. that's every customer who ever ordered.
EXCEPT is the useful one here: 191 customers ordered last year and haven't been back. it's an anti join written as a set operation, and for a single column of keys it reads very naturally. (the count(*) FROM (...) AS x wrapper is just there to count, the set operation is the inside.)
SELECT count(*) FROM (
SELECT customer_id FROM orders
UNION
SELECT customer_id FROM orders
) AS x;SELECT count(*) FROM (
SELECT customer_id FROM orders
UNION
SELECT customer_id FROM orders
) AS x;| countint8 |
|---|
| 1962 |
UNION ALL is usually what you meant
UNION has to find duplicates, and finding duplicates means hashing or sorting every row. UNION ALL just appends one result to the other:
so reach for UNION ALL first, and use UNION only when you actually want duplicates gone. two common cases where UNION ALL is simply right:
- the two sides can't overlap. last year's orders and this year's orders, active users and deleted users, the
eutable and theustable. there's nothing to deduplicate, and UNION spends a hash table finding that out. - the duplicates are real. two order lines with the same product and the same quantity are two lines. stack them with UNION and one of them vanishes, and every sum after that is short.
the rules
both sides need the same number of columns, with types that can be matched up. the result takes its column names from the first query. and columns are paired by position. names don't matter, so this runs without a word of complaint:
SELECT name, city FROM customers WHERE id = 42
UNION ALL
SELECT city, name FROM customers WHERE id = 8
ORDER BY name;| nametext | citytext |
|---|---|
| Ada Lovelace | London |
| Dublin | Sean O'Neil |
Dublin is now a name and Sean O'Neil is a city. if the types don't fit, postgres does notice:
SELECT id FROM customers
UNION
SELECT name FROM customers;two more:
- a final
ORDER BYorLIMITapplies to the whole combined result, not to the last query. to sort or limit one side, put that side in parentheses. - that final ORDER BY can only use the result's column names (the first query's) or positions. a name that only the second query used is an error:
SELECT 1 AS a
UNION
SELECT 2 AS b
ORDER BY b;keylines
- set operations stack results: UNION (either), INTERSECT (both), EXCEPT (first, not second).
- without ALL they remove every duplicate, inside each side too.
- UNION ALL skips the deduplication: faster, and it never drops equal rows.
- columns pair up by position. names come from the first query.
- two NULLs count as the same row here, unlike in a join's ON.