r/SQL • u/MrRoy_SQL • 24d ago
Discussion your LEFT JOIN might secretly be an INNER JOIN (the WHERE clause trap)
ran into this recently so posting it for anyone newer to joins.
two tiny tables:
customers orders
id | name id | customer_id | status
1 | Asha 1 | 1 | completed
2 | Ben 2 | 1 | refunded
3 | Chen 3 | 2 | completed
4 | Dina 4 | 3 | refunded
question: completed orders per customer, **including customers with 0**.
first try:
SELECT c.name, COUNT(o.id) AS completed_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'completed'
GROUP BY c.name;
result:
Asha | 1
Ben | 1
Chen and Dina are gone. the LEFT JOIN did its job and kept them (with NULLs for the order columns), but then WHERE runs after the join and `NULL = 'completed'` isn't true, so those rows get thrown out. Chen's only order is refunded so he gets dropped too. end result is exactly what an INNER JOIN would give you.
fix: move the filter into the ON:
SELECT c.name, COUNT(o.id) AS completed_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
AND o.status = 'completed'
GROUP BY c.name;
Asha | 1
Ben | 1
Chen | 0
Dina | 0
now the filter decides which orders get matched, not which customers survive.
rule I use: on a LEFT JOIN, conditions on the right table go in ON. conditions on the left table go in WHERE. (and use COUNT(o.id) not COUNT(*), otherwise Chen and Dina show 1 instead of 0)
13
u/ElHombrePelicano 24d ago edited 24d ago
No. Your left joins are still left joins and your where clauses are still your where clauses.
1
u/RajeshRocketMan 23d ago
I’ve seen this break so many reports: someone adds a status filter to an old query and nobody notices. Moving the condition into the ON clause is the right fix.
0
u/alertetainry 24d ago
SQL really has a talent for giving you a completely valid query that returns exactly the wrong answer