ON vs WHERE in OUTER JOINs in SQL
The silent-INNER bug every review must catch
ON decides matching during the join — non-matching left rows survive a LEFT JOIN with NULLs. WHERE filters after — testing the nullable side kills the NULL rows, silently converting LEFT into INNER. Rule: match conditions in ON; keep outer-ness by testing nullable columns only for IS NULL or moving filters into ON.
ON matches during
Decides pairing inside the join. Unmatched LEFT rows survive as NULLs.
WHERE filters after
Tests the joined result. NULL-side tests fail — orphans vanish.
Silent-INNER mechanism
WHERE d.x = 1 after LEFT JOIN kills NULLs — LEFT behaves as INNER with no error.
Placement rule
Optional-side predicates in ON; IS NULL orphan checks stay in WHERE.
1SELECT e.name, d.location FROM employees e LEFT JOIN departments d ON e.department = d.dept_id AND d.location = 'Berlin';
| name | location |
|---|---|
| Alice | Berlin |
| Bob | null |
| Cynthia | Berlin |
| David | null |
| Elena | null |
| Farid | Berlin |
Berlin matches survive with location filled; everyone else survives with NULL. Move the location test to WHERE and the NULL rows vanish — the LEFT silently behaves as INNER.
Filter in ON — stays LEFT
Berlin matches fill, others NULL-fill and survive.
1SELECT e.name, d.location FROM employees e LEFT JOIN departments d ON e.department = d.dept_id AND d.location = 'Berlin';
| name | location |
|---|---|
| Alice | Berlin |
| Bob | null |
| Cynthia | Berlin |
| David | null |
| Elena | null |
| Farid | Berlin |
Filter in WHERE — becomes INNER
Same predicate, different placement, fewer rows.
1SELECT e.name, d.location FROM employees e LEFT JOIN departments d ON e.department = d.dept_id WHERE d.location = 'Berlin';
| name | location |
|---|---|
| Alice | Berlin |
| Cynthia | Berlin |
| Farid | Berlin |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.