Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 06 / Topic 8 of 8

UNION, INTERSECT, EXCEPT

Joins combine tables sideways; set operations stack result sets vertically. The inputs must have the same column count and compatible types.

SELECT city FROM customers WHERE city IS NOT NULL
UNION
SELECT country FROM suppliers
ORDER BY city;
  city   
---------
 Chennai
 Delhi
 Germany
 India
 London
 Pune
 UK
(7 rows)

One list of places, duplicates removed — because UNION de-duplicates, like DISTINCT:

SELECT 1 UNION SELECT 1;
 ?column? 
----------
        1
(1 row)

One row. UNION ALL keeps duplicates — and skips the de-duplication work, so it's both more correct for "stack these logs/periods together" jobs and faster. Default to ALL unless you specifically want de-duplication.

INTERSECT keeps rows in both; EXCEPT keeps the first set minus the second — customer ids who viewed something but never purchased:

SELECT customer_id FROM events WHERE event_type = 'view'
EXCEPT
SELECT customer_id FROM events WHERE event_type = 'purchase'
ORDER BY customer_id;
 customer_id 
-------------
           6
(1 row)

🧪 Quick quiz — answer from memory, then check.

  1. SELECT 1 UNION SELECT 1; returns how many rows?
  2. When should you write UNION ALL?
Show the answers
  1. 1 — UNION removes duplicates. UNION ALL would return 2.
  2. Whenever duplicates are impossible or wanted — it's the faster default; plain UNION only when you need the de-dup.

Exercise 8: Carted, never bought

What to do: Which customer ids have a cart event but no purchase event? One set operation does it.

Sample output:

 customer_id 
-------------
           6
(1 row)

💡 Hint: EXCEPT. (Customer 6 is Vikram — the browsing non-buyer strikes again.)

Show the solution to Exercise 8
-- Exercise 8: Carted, never bought
SELECT customer_id FROM events WHERE event_type = 'cart'
EXCEPT
SELECT customer_id FROM events WHERE event_type = 'purchase'
ORDER BY customer_id;

Search the guide