Keeping unmatched rows: LEFT JOIN
Stage 4: Joins · Lesson 15 of 17 · 6 min read · free, interactive
A plain JOIN (an inner join) drops rows that have no match. Players who never bought anything vanish:
SELECT p.name, pu.id AS purchase_id
FROM players p
JOIN purchases pu ON pu.player_id = p.id;
LEFT JOIN keeps every row of the left table. Where there is no match, the right table's columns are NULL:
SELECT p.name, pu.id AS purchase_id
FROM players p
LEFT JOIN purchases pu ON pu.player_id = p.id;
That NULL is useful: "rows with no match" is a LEFT JOIN followed by IS NULL on the right side.
SELECT p.name
FROM players p
LEFT JOIN purchases pu ON pu.player_id = p.id
WHERE pu.id IS NULL;
Practice
Each answer runs in your browser and is checked on hidden data.
- Write the query: Return every player's
namewith theidof each of their purchases aspurchase_id. Players who never bought anything appear once, with NULL. Row order does not matter. - Find the bug: Return the
nameof every item that nobody has bought. Row order does not matter. - Fill in the blanks: Return the
nameof every player who has never made a purchase. Row order does not matter.
Previous: Combining tables with JOIN · Next: Joining a table to itself · All lessons