SQL · Module 8 · Lesson 61 min read

Set Operations: UNION, INTERSECT & EXCEPT

Set operations combine the results of two queries vertically (rows), while joins combine horizontally (columns).

The operators

OperatorReturns
UNIONrows from both queries, duplicates removed
UNION ALLrows from both, keeps duplicates (faster ✅)
INTERSECTrows that appear in both
EXCEPTrows in the first query but not in the second

INTERSECT ALL and EXCEPT ALL keep duplicate counts. (Oracle calls EXCEPT MINUS.)

Rules

  1. Both queries must return the same number of columns
  2. Matching columns must have compatible types
  3. Column names come from the first query
  4. ORDER BY / LIMIT apply to the whole combined result (written once, at the end)
  5. Wrap a part in parentheses if it needs its own ORDER BY / LIMIT

UNION vs UNION ALL

UNION has to sort or hash all rows to remove duplicates. If duplicates are impossible or acceptable, use UNION ALL — it's faster.

Common uses

  • One activity feed from several tables (expenses + bills + accounts)
  • Combining data from archive and current tables
  • Comparing lists: users in both lists (INTERSECT), new users this month (EXCEPT)
  • Adding a "total" row to a report (or use ROLLUP)

Add a constant column to show where each row came from: SELECT 'expense' AS type, …

Example

SQL
-- Activity feed: expenses and bills in one list
SELECT 'expense' AS type, user_id, title, amount, spent_on AS on_date
FROM expenses WHERE user_id = 1 AND spent_on >= '2026-11-01'
UNION ALL
SELECT 'bill', user_id, title, amount, due_date
FROM bills WHERE user_id = 1
ORDER BY on_date;
-- expense Movie tickets ... bill Internet 2026-11-25, bill Rent 2026-12-01

-- UNION removes duplicates, UNION ALL keeps them
SELECT title FROM expenses WHERE title LIKE 'Electricity%'
UNION
SELECT title FROM bills;                -- 'Electricity bill' once + bill titles

SELECT count(*) FROM (
  SELECT title FROM expenses WHERE title LIKE 'Electricity%'
  UNION ALL
  SELECT title FROM bills
) t;                                     -- 4 + 5 = 9

-- INTERSECT: users who spent in BOTH September and November
SELECT user_id FROM expenses WHERE spent_on < '2026-10-01'
INTERSECT
SELECT user_id FROM expenses WHERE spent_on >= '2026-11-01'
ORDER BY user_id;                        -- 1, 2, 3, 4

-- EXCEPT: categories used in October but not in November
SELECT c.name FROM expenses e JOIN categories c ON c.id = e.category_id
WHERE e.spent_on >= '2026-10-01' AND e.spent_on < '2026-11-01'
EXCEPT
SELECT c.name FROM expenses e JOIN categories c ON c.id = e.category_id
WHERE e.spent_on >= '2026-11-01';
-- Internet (no internet bill was logged in November)

-- Report with a total row
SELECT name::text AS label, monthly_budget FROM users WHERE monthly_budget IS NOT NULL
UNION ALL
SELECT 'TOTAL', sum(monthly_budget) FROM users;