Skip to content

Statement set operators: UNION, EXCEPT, INTERSECT

View as Markdown

Statement set operators combine the results of two or more queries into one result.

query_term set_operator [DISTINCT | DISTINCTROW | UNIQUE | ALL] query_term
[set_operator [...] query_term ...]
[ORDER BY ...] [LIMIT ...]
set_operator ::= UNION | DIFFERENCE | EXCEPT | INTERSECTION | INTERSECT
Operator Result
UNION The rows returned by either query.
DIFFERENCE, EXCEPT The rows returned by the first query but not by the second.
INTERSECTION, INTERSECT The rows returned by both queries.
  • By default (or with DISTINCT, DISTINCTROW or UNIQUE), duplicate rows are removed from the result. With ALL, they are kept: UNION ALL returns every row of both queries, and EXCEPT ALL and INTERSECT ALL count duplicates.
  • The queries must return the same number of columns, with compatible types. The column names of the result are those of the first query.
  • An ORDER BY or LIMIT at the end applies to the combined result.
  • UNION ALL is the cheapest, because it does not have to look for duplicates. Use it when duplicates are impossible or wanted.

The customers who ordered in December 2024 and in December 2025. Each query returns one row per order, so customers with several orders appear several times.

UNION returns each customer who ordered in either month once; UNION ALL returns one row for each of the 94 + 95 orders:

SELECT COUNT(*) FROM (
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31'
UNION
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31'
) t;
count(*)
149
SELECT COUNT(*) FROM (
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31'
UNION ALL
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31'
) t;
count(*)
189

The customers who ordered in both months:

SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31'
INTERSECT
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31'
ORDER BY 1
LIMIT 5;
customer_id
32
129
209
223
267

There are 16 of them. The customers who ordered in December 2024 but not in December 2025:

SELECT COUNT(*) FROM (
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31'
EXCEPT
SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31'
) t;
count(*)
67

The queries can read different tables, as long as their columns match. Brand and category names that start with N:

SELECT name FROM brand WHERE name LIKE 'N%'
UNION
SELECT name FROM category WHERE name LIKE 'N%'
ORDER BY 1;
name
New Balance
New Luma Yoga Collection
Nike