Skip to content
Cheatsheets / SQL Set Operations Cheatsheet
Cheatsheet

SQL Set Operations Cheatsheet

UNION, UNION ALL, INTERSECT, and EXCEPT side by side.

The four operators

Operator Keeps Duplicates
UNION ALL All rows from both Kept
UNION All rows from both Removed
INTERSECT Rows in both Removed
EXCEPT Rows in the first only Removed

Set operations combine or compare compatible result sets by row. A UNION stacks rows, while INTERSECT and EXCEPT keep only rows that satisfy the set relationship. Joins, by contrast, combine rows based on a relationship and can add columns from both inputs.

The shape

One ORDER BY, at the very end
select state from customers
union all
select state from suppliers
order by state

Compatibility rules

  • Every SELECT returns the same number of columns.
  • Matching columns have compatible types.
  • Output column names come from the first SELECT.

Common jobs

Stack two sources (keep everything)
select 'customer' as source, state from customers
union all
select 'supplier',            state from suppliers
Values shared by both (overlap)
select state from customers
intersect
select state from suppliers
In the first, not the second (missing list)
select customer_id from customers
except
select customer_id from orders
Watch out

Prefer UNION ALL when duplicate preservation is correct for the question. UNION performs duplicate elimination, which adds work and can change row counts. Put the final ORDER BY after the set expression; without a final ordering, do not rely on result order.