Combining tables with JOIN
Stage 4: Joins · Lesson 14 of 17 · 6 min read · free, interactive
purchases only stores ids: player_id points to a row in players, item_id to a row in items. These are foreign keys — open the schema diagram below to see the links.
JOIN … ON pairs each row with the matching row of another table. Short table aliases (pu, p) keep it readable:
SELECT pu.id, p.name, pu.qty
FROM purchases pu
JOIN players p ON p.id = pu.player_id;
Chain joins to pull in more tables:
SELECT p.name, i.name AS item, pu.qty
FROM purchases pu
JOIN players p ON p.id = pu.player_id
JOIN items i ON i.id = pu.item_id;
Tip: When two tables have a column with the same name (both have name and id), prefix it with the alias: p.name, i.name.
Practice
Each answer runs in your browser and is checked on hidden data.
- Write the query: For every purchase, return its
idand the buyer'sname. Row order does not matter. - Fill in the blanks: For every purchase, return its
idand the name of the item bought asitem. Row order does not matter. - Find the bug: For every purchase, return the buyer's
nameand the item's name asitem. Row order does not matter.
Previous: Counting distinct values · Next: Keeping unmatched rows: LEFT JOIN · All lessons