Joins
Inner vs left, anti-joins, and the fan-out trap
45 min · interactive lesson with runnable code and 6 graded exercises.
What you'll be able to do
- Choose between INNER and LEFT JOIN from the question
- Find rows with no match (anti-join)
- Spot the WHERE clause that silently turns a left join into an inner join
- Prevent fan-out by aggregating before joining
INNER JOIN
Only rows that match on both sides
A join lines up rows from two tables on a key. INNER JOIN keeps a row only when the key exists in both tables.
LEFT JOIN
Keep everyone from the left table
LEFT JOIN keeps every row of the left table; where there is no match, the right side's columns are NULL. Start from the entity you're reporting on (customers) so nobody disappears.
Finding what's missing
Anti-joins
“Customers with no orders” is a left join + IS NULL on the right key. NOT EXISTS says the same thing and is often clearer.
The WHERE trap
Why did my left join drop rows?
A filter on the right table in WHERE removes the NULL rows the left join kept — your left join silently becomes an inner join. Put such filters in the ON clause.
Fan-out
When a join multiplies rows
Joining one row to many rows repeats it. Join customers to orders and events at once, and each order is repeated once per event — totals explode.
Self-joins and CTEs
A table joined to itself
A CTE (WITH name AS (…)) names a sub-result so the main query reads top to bottom. A self-join joins a table to itself — e.g. pairs of customers in the same city on the same plan.