Multi-table Joins & ON vs WHERE
Build joins one table at a time
- Start from the table that defines one row of your result (e.g. users for "one row per user")
- Add one join, run it, check the row count
- Add the next join… and repeat
⚠️ Row multiplication (fan-out)
Joining two one-to-many tables to the same parent multiplies rows:
- Asha has 10 expenses and 2 accounts → joining both gives 20 rows
sum(e.amount)is now doubled andsum(a.balance)is counted 10 times! ❌
Fixes
- Aggregate first, then join (subqueries or CTEs) ✅
- Or use
count(DISTINCT …)(works for counts, but not for sums)
Choosing INNER vs LEFT in a chain
Once you LEFT JOIN a table, later joins to it should usually also be LEFT JOINs — an INNER JOIN on a NULL-filled row removes it again.
ON vs WHERE (summary)
| INNER JOIN | LEFT JOIN | |
|---|---|---|
| Condition in ON | same result as WHERE | limits which right rows match; left rows stay |
| Condition in WHERE | filters the result | filters after the join; right-table conditions remove unmatched rows |
Readability tips
- One
JOINper line, with itsONunderneath - Consistent aliases (
u,e,c,a,b) - Join on keys, filter in WHERE (except LEFT JOIN right-side filters)
- Long query? Break it into CTEs (Unit 8)
Join performance
Joins on indexed keys are fast even for millions of rows. The planner picks a strategy (nested loop, hash join, merge join) — see EXPLAIN in Unit 11.
Example
-- ❌ Fan-out: joining expenses AND accounts multiplies rows
SELECT u.name,
count(*) AS joined_rows,
sum(e.amount) AS wrong_spent,
sum(a.balance) AS wrong_balance
FROM users u
JOIN expenses e ON e.user_id = u.id
JOIN accounts a ON a.user_id = u.id
WHERE u.id = 1
GROUP BY u.name;
-- Asha | 20 rows | 43940.00 (should be 21970) | 900000.00 (should be 90000)
-- ✅ Aggregate each side first, then join
SELECT u.name,
COALESCE(e.spent, 0) AS spent,
COALESCE(a.balance, 0) AS balance,
COALESCE(b.unpaid, 0) AS unpaid_bills
FROM users u
LEFT JOIN (SELECT user_id, sum(amount) AS spent FROM expenses GROUP BY user_id) e ON e.user_id = u.id
LEFT JOIN (SELECT user_id, sum(balance) AS balance FROM accounts GROUP BY user_id) a ON a.user_id = u.id
LEFT JOIN (SELECT user_id, sum(amount) AS unpaid FROM bills WHERE NOT paid GROUP BY user_id) b ON b.user_id = u.id
ORDER BY u.id;
-- Asha Sharma | 21970.00 | 90000.00 | 16500.00 ...
-- A 4-table report: November spending by city and parent category
SELECT COALESCE(u.city, 'Unknown') AS city,
COALESCE(parent.name, c.name) AS main_category,
sum(e.amount) AS total
FROM expenses e
JOIN users u ON u.id = e.user_id
JOIN categories c ON c.id = e.category_id
LEFT JOIN categories parent ON parent.id = c.parent_id
WHERE e.spent_on >= '2026-11-01'
GROUP BY 1, 2
ORDER BY 1, total DESC;