Inner and outer joins
Most explanations of joins are Venn diagrams. They are memorable and they do not help, because the question an interviewer asks is not “which circles overlap” — it is “how many rows does this return, and why is one of them missing”.
So this lesson is about rows.
The data
Two things in the fixture matter for every example below:
- Grace has no department.
employee.department_idisNULLfor her. - Research has no employees. It is a
departmentrow nothing references.
Those two rows are what make the join types differ at all. A dataset where every
row matches makes INNER and LEFT return the same thing, which is why
examples built on tidy data teach nothing.
INNER JOIN — only rows that matched
SELECT e.name, d.name AS department
FROM employee e
JOIN department d ON d.id = e.department_id
ORDER BY e.name;
Six rows. Grace is gone, because there is nothing to pair her with, and Research
is gone, because no employee points at it. JOIN means INNER JOIN; the word
is optional and worth writing anyway, since LEFT JOIN spells its side out and
a bare JOIN next to it reads as an oversight.
LEFT JOIN — every left row, matched or not
SELECT e.name, d.name AS department
FROM employee e
LEFT JOIN department d ON d.id = e.department_id
ORDER BY e.name;
Seven rows. Grace is back, with NULL for department. The left table’s rows
are all preserved; the right table’s columns are filled with NULL where there
was no match.
Reverse the tables and you get the other direction:
SELECT d.name AS department, e.name
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
ORDER BY d.name, e.name;
Now Research appears with a NULL employee, and Grace is gone. LEFT JOIN is
not symmetric — which side you put first changes the answer.
RIGHT JOIN — the same thing, written backwards
a RIGHT JOIN b is b LEFT JOIN a with the columns reordered. It exists, it is
legal, and in practice it mostly appears in code where someone added a table to
the front of a FROM clause and fixed the breakage with the wrong keyword. Pick
LEFT and keep the preserved table on the left; a reader then only has to hold
one rule.
FULL OUTER JOIN — every row from both sides
SELECT e.name, d.name AS department
FROM employee e
FULL OUTER JOIN department d ON d.id = e.department_id
ORDER BY d.name, e.name;
Eight rows: the six that matched, plus Grace with a NULL department, plus
Research with a NULL employee. Genuinely useful for reconciliation — “what is
in one system and not the other, in both directions” — and rare otherwise.
The trap: ON versus WHERE in an outer join
This is the part that gets asked, and the part that quietly produces wrong numbers in real code.
SELECT d.name AS department, e.name
FROM department d
LEFT JOIN employee e ON e.department_id = d.id AND e.salary > 90000
ORDER BY d.name, e.name;
Every department still appears. The salary condition is part of how rows are
matched, so departments with no highly-paid employee come back with a NULL
employee rather than disappearing.
Now move one word:
SELECT d.name AS department, e.name
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
WHERE e.salary > 90000
ORDER BY d.name, e.name;
Support and Research are gone. The LEFT JOIN produced their rows with NULL
employee columns, and then WHERE e.salary > 90000 evaluated NULL > 90000,
which is unknown, which is not true — so those rows were discarded. A WHERE
clause on the nullable side of an outer join turns it back into an inner join.
The rule, from the previous lesson’s order of operations: ON is part of step 1,
WHERE is step 2. Anything you want to affect matching goes in ON; anything
you want to affect the final row set goes in WHERE. For an inner join the
two are interchangeable and it does not matter. For an outer join it is the
difference between four departments and two.
Finding rows with no match
The outer join plus an IS NULL test is the idiomatic “anti-join”:
SELECT d.name AS department
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
WHERE e.id IS NULL;
Research, and only Research. Note the test is on e.id — the right table’s
primary key, which can only be NULL when there was no match. Testing a
nullable column instead would conflate “no match” with “matched a row whose
value happens to be NULL”.
There is a NOT EXISTS form of the same query that is usually clearer and
sometimes faster, and a NOT IN form that is a trap. Both are in
NULLs in joins and filters.
Try it
Open the SQL playground and run the ON-versus-WHERE pair
back to back. Seeing four rows become two is more convincing than reading that
it happens.
The drill is
Employees without a manager, where
INNER and LEFT give different answers on the same table, and
Sales per employee including the quiet ones.
For where joins fit in a system rather than a query — and why a denormalised store sometimes exists precisely to avoid them — see SQL vs NoSQL.
Interview questions
1. What is the difference between an INNER JOIN and a LEFT JOIN?
INNER returns only rows that matched on both sides. LEFT returns every row
from the left table, filling the right table’s columns with NULL where nothing
matched.
2. Is LEFT JOIN symmetric? What happens if you swap the tables?
It is not. Swapping the tables changes which side is preserved, so you get a
different row set. a RIGHT JOIN b is the same as b LEFT JOIN a.
3. Why does adding a WHERE clause to a LEFT JOIN sometimes turn it into an
inner join?
Because the outer join produces NULLs for unmatched rows, and a WHERE
condition on one of those NULL columns evaluates to unknown rather than true,
so the row is discarded. Putting the condition in ON instead keeps it part of
matching.
4. How would you find all departments with no employees?
LEFT JOIN the employees and test the right table’s primary key for IS NULL;
or NOT EXISTS with a correlated subquery. Not NOT IN against a nullable
column — see the NULL lesson for why.
5. When would you reach for a FULL OUTER JOIN?
Reconciliation between two sources where you need the unmatched rows from both
directions at once, such as comparing a ledger against a statement.
6. Does the order of tables in an INNER JOIN change the result?
Not the result. It may change the plan — which table the planner builds a hash
on, for example — but the row set is identical, which is exactly why the planner
is allowed to reorder them.
Next
Join pitfalls and the grain problem — where a join that looks right returns twice the money.