Memra

UNION, INTERSECT & EXCEPT

◈ 2 cards

Combine the rows of two queries as sets.

Stack query results

Set operators combine the rows of two SELECTs that have the same columns:

  • UNION — all rows from both, duplicates removed
  • UNION ALL — all rows, duplicates kept (faster — use when you know there are none)
  • INTERSECT — only rows in both
  • EXCEPT — rows in the first but not the second
SELECT book_id FROM order_items
INTERSECT
SELECT book_id FROM reviews;

Column names come from the first query; the column types must line up.

operatorresult on book_idUNION1,2,3,4,5,6,7,9,10UNION ALL21 rows, duplicates keptINTERSECT1,2,4,5,6,7EXCEPT3,9,10Left = ordered ids, right = reviewed ids.
Ordered ids are 1–7, 9 and 10; reviewed ids are 1, 2 and 4–7. EXCEPT is the ordered-but-never-reviewed answer, INTERSECT is the overlap, and UNION ALL is the only one that keeps duplicates.
NORMAL ~/memra/learn/postgresql/set-operations utf-8 LF