UNION, INTERSECT and EXCEPT in PostgreSQL
Learn PostgreSQL's set operators — UNION and UNION ALL for combining results, INTERSECT for common rows, and EXCEPT for rows in one query but not another.
UNION, INTERSECT and EXCEPT
Set operators combine the results of two separate SELECT queries — both queries must return the same number of columns, with compatible types.
UNION — Combine Rows, Remove Duplicates
SELECT name FROM employees
UNION
SELECT name FROM contractors;
-- every distinct name across both tables
UNION ALL — Combine Rows, Keep Duplicates
Faster than UNION since it skips the work of de-duplicating — use it whenever you know there won't be (or don't care about) duplicates.
SELECT name FROM employees
UNION ALL
SELECT name FROM contractors;
INTERSECT — Rows in Both Queries
SELECT email FROM employees
INTERSECT
SELECT email FROM newsletter_subscribers;
-- employees who are ALSO subscribed to the newsletter
EXCEPT — Rows in the First Query, Not the Second
SELECT email FROM employees
EXCEPT
SELECT email FROM newsletter_subscribers;
-- employees who are NOT subscribed to the newsletter
The order matters — A EXCEPT B is not the same as B EXCEPT A.
Advertisement728 x 90
Common Errors & Troubleshooting
ERROR: each UNION query must have the same number of columns— bothSELECTs must return the exact same column count; add a placeholder (likeNULL AS extra_col) to the shorter query if needed.ERROR: UNION types text and integer cannot be matched— the corresponding columns' types must be compatible; cast one side explicitly (column::TEXT) if they genuinely represent the same kind of information stored differently.- Using
UNIONwhenUNION ALLwas intended, and eating a performance cost —UNIONalways de-duplicates the combined result, which requires an extra sort/comparison step; if you already know there are no duplicates (or don't care),UNION ALLis faster.
Key Takeaways
- All three operators require the two queries to return the same number of columns with compatible types.
UNIONdeduplicates by default;UNION ALLkeeps every row and is faster.EXCEPTis order-sensitive — it means "in the first result set, but not the second."
Advertisement320 x 100