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

Part 05 / Topic 9 of 9

Semi-joins and anti-joins

Two everyday questions wear fancy names:

  • Semi-join — "customers who have ordered" (match exists; don't duplicate anyone)
  • Anti-join — "customers who never ordered" (no match exists)

You met the anti-join in section 3 (LEFT JOIN ... WHERE IS NULL). The other standard spelling uses EXISTS, which asks only "is there at least one?" — no duplication possible, intent on the surface:

SELECT c.first_name
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id)
ORDER BY c.customer_id;
 first_name 
------------
 Asha
 Ravi
 Meera
 John
 Sara
(5 rows)
SELECT c.first_name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id);
 first_name 
------------
 Vikram
(1 row)

That (SELECT ...) inside the WHERE is a subquery — Part 6 opens it up fully (including why its cousin NOT IN has a NULL-shaped trap). For now: EXISTS/NOT EXISTS read exactly like the question, and a plain JOIN used as a semi-join would duplicate customers with several orders — Asha three times, not once.

🧪 Quick quiz — answer from memory, then check.

  1. Why can a plain JOIN not serve as a semi-join directly?
  2. Two spellings of "customers who never ordered"?
Show the answers
  1. It returns one row per match — a customer with 3 orders appears 3 times. EXISTS checks for at least one match without multiplying.
  2. LEFT JOIN ... WHERE right.key IS NULL, or WHERE NOT EXISTS (...).

Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.

Search the guide