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.

Previous: Combining tables with JOIN · Next: Joining a table to itself · All lessons