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
select state from customers
union all
select state from suppliers
order by state Compatibility rules
-
Every
SELECTreturns the same number of columns. - Matching columns have compatible types.
-
Output column names come from the first
SELECT.
Common jobs
select 'customer' as source, state from customers
union all
select 'supplier', state from suppliers select state from customers
intersect
select state from suppliers select customer_id from customers
except
select customer_id from orders
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.
Related
Use WHERE to keep only matching rows.
Comparisons, AND/OR, IN, BETWEEN, and LIKE.
Practice ranking, running totals, and top row per group.
Debug filters that match nothing.
Filter window results in a CTE or with QUALIFY.
Combine filters without changing the intended logic.