LEFT JOIN and rows without a match
128 min
INNER JOIN silently drops the rows that have no match. Yet often those are exactly the interesting ones: “customers who never ordered”, “groups without a curator”, “students without a single grade”.
LEFT JOIN
Every row of the left table stays. Where there is no match in the right table, its columns come out as NULL.
Groups without a curator show NULL as curator.
Finding the rows without a match
The most useful trick: LEFT JOIN + WHERE right.id IS NULL.
These are the customers who have never placed an order.
RIGHT JOIN and FULL JOIN
RIGHT JOINmirrorsLEFT JOIN: the right table stays complete. It is usually clearer to swap the tables and writeLEFT JOIN.FULL JOINkeeps the unmatched rows from both sides.
PostgreSQL supports FULL OUTER JOIN.
Careful: is the condition in WHERE or in ON?
In a LEFT JOIN, a condition on the right table written in WHERE rejects the unmatched rows (the NULLs), and the LEFT JOIN quietly becomes a plain JOIN. A condition on the right table belongs in ON:
COUNT(o.id) does not count NULLs, so a customer without cancelled orders gets 0.
Show the names of the products that have no reviews at all (reviews).
Show each faculty’s name and the number of its teachers. A faculty without teachers should show 0.
Remember
LEFT JOINkeeps the whole left table; unmatched rows getNULLon the right.- Rows without a match:
LEFT JOIN … WHERE right.id IS NULL. - Conditions on the right table go in
ON, or theLEFT JOINstops working.