skip to content

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.

op =
ALL =
query.sql
  1. 1SELECT item FROM ada UNION SELECT item FROM sean ORDER BY item NULLS LAST;
ada
kettlekettlekettlewhisknull
sean
atlaskettlekettlenull
UNION: 4 rows
atlaskettlewhisknull
itemm, adan, seanout
atlas011
kettle321
whisk101
null111
out = 1 if it's on either side

UNION: every distinct item from either basket, once. the two NULLs count as the same item.

real output, postgres 18.6 (PGlite 0.5.12) · bags
pick an operation, then flip ALL. the table counts copies: m in Ada's basket, n in Sean's, and how many came out. without ALL every item comes out at most once. and 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?

combine with =
query.sql
  1. 1SELECT count(*) AS customers FROM (
  2. 2 SELECT customer_id FROM orders WHERE ordered_at < timestamptz '2026-01-01 00:00+00'
  3. 3 UNION
  4. 4 SELECT customer_id FROM orders WHERE ordered_at >= timestamptz '2026-01-01 00:00+00'
  5. 5) AS x;
the result for UNION
customersint8
1962
(1 row)

UNION: customers who ordered in either year, each once. that's every customer who ever ordered.

real output, postgres 18.6 (PGlite 0.5.12) · set-shop
switch the operation. UNION finds the 1,962 customers who ever ordered. UNION ALL keeps a row per order, so it counts all 10,000 orders. INTERSECT is the customers who came back, EXCEPT the ones who didn't.

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

predict the output
sql
SELECT count(*) FROM (
  SELECT customer_id FROM orders
  UNION
  SELECT customer_id FROM orders
) AS x;
sqldb=shop
SELECT count(*) FROM (
  SELECT customer_id FROM orders
  UNION
  SELECT customer_id FROM orders
) AS x;
output, from postgres 18.6
SELECT 1
countint8
1962
(1 row)

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:

show =
estimated rows
the two plans for the 2025 and 2026 customer lists. UNION adds a HashAggregate on top of the Append, to throw duplicates away. UNION ALL is only the Append.

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 eu table and the us table. 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:

sqldb=shop
SELECT name, city FROM customers WHERE id = 42
UNION ALL
SELECT city, name FROM customers WHERE id = 8
ORDER BY name;
output, from postgres 18.6
SELECT 2
nametextcitytext
Ada LovelaceLondon
DublinSean O'Neil
(2 rows)

Dublin is now a name and Sean O'Neil is a city. if the types don't fit, postgres does notice:

sqldb=shop
SELECT id FROM customers
UNION
SELECT name FROM customers;
output, from postgres 18.6
ERROR 42804: UNION types integer and text cannot be matched
3 │ SELECT name FROM customers;
at line 3, column 8

two more:

  • a final ORDER BY or LIMIT applies 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:
sqlempty db
SELECT 1 AS a
UNION
SELECT 2 AS b
ORDER BY b;
output, from postgres 18.6
ERROR 42703: column "b" does not exist
4 │ ORDER BY b;
at line 4, column 10
DETAIL: There is a column named "b" in table "*SELECT* 2", but it cannot be referenced from this part of the query.

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.