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

OperatorKeepsDuplicates
UNION ALLAll rows from bothKept
UNIONAll rows from bothRemoved
INTERSECTRows in bothRemoved
EXCEPTRows in the first onlyRemoved

They stack results vertically (more rows), unlike joins, which add columns.

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

Common jobs

Stack two sources (keep everything)
select order_id, 'web' as channel from web_orders
union all
select order_id, 'store'      from store_orders
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 unless you truly need to remove duplicates -UNION pays to sort and dedupe. Put a single ORDER BYafter the last SELECT; ordering the inputs won't control the combined order.