UNION, INTERSECT, and EXCEPT
- Version
- 19
- Review
- Draft
Summary#
UNION combines rows from either query, INTERSECT keeps rows found in both, and EXCEPT keeps rows from the left query that are absent from the right query. The default forms remove duplicate output rows.
Syntax#
query_a UNION [ALL] query_b
query_a INTERSECT [ALL] query_b
query_a EXCEPT [ALL] query_b
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE morning_pickups (bin integer NOT NULL);
CREATE TEMPORARY TABLE evening_pickups (bin integer NOT NULL);
INSERT INTO morning_pickups VALUES (10), (10), (20);
INSERT INTO evening_pickups VALUES (20), (30);
SELECT bin FROM morning_pickups
UNION
SELECT bin FROM evening_pickups
ORDER BY bin;
SELECT bin FROM morning_pickups
UNION ALL
SELECT bin FROM evening_pickups
ORDER BY bin;
SELECT bin FROM morning_pickups
INTERSECT
SELECT bin FROM evening_pickups
ORDER BY bin;
SELECT bin FROM morning_pickups
EXCEPT
SELECT bin FROM evening_pickups
ORDER BY bin;
ROLLBACK;
Expected output#
bin
10
20
30
(3 rows)
bin
10
10
20
20
30
(5 rows)
bin
20
(1 row)
bin
10
(1 row)
Common mistakes#
Each query must return the same number of columns, with compatible types at each position. Use UNION ALL to retain duplicates and an outer ORDER BY to sort the combined result. With INTERSECT ALL, each match uses one copy from each side. With EXCEPT ALL, each right-side copy removes one left-side copy. Parenthesize a branch when its LIMIT applies only to that branch. INTERSECT binds more tightly than UNION or EXCEPT.
Version applicability#
These set operations and their ALL forms work in PostgreSQL 19.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0