Statement set operators: UNION, EXCEPT, INTERSECT
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,DISTINCTROWorUNIQUE), duplicate rows are removed from the result. WithALL, they are kept:UNION ALLreturns every row of both queries, andEXCEPT ALLandINTERSECT ALLcount 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 BYorLIMITat the end applies to the combined result. UNION ALLis the cheapest, because it does not have to look for duplicates. Use it when duplicates are impossible or wanted.
Examples
Section titled “Examples”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'INTERSECTSELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31'ORDER BY 1LIMIT 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%'UNIONSELECT name FROM category WHERE name LIKE 'N%'ORDER BY 1;| name |
|---|
| New Balance |
| New Luma Yoga Collection |
| Nike |
See also
Section titled “See also”- SELECT
- Set arithmetic operators: the same operations on collection values