Joining a table to itself
Stage 4: Joins · Lesson 16 of 17 · 6 min read · free, interactive
A table can be joined to itself. players.mentor_id points to another player, so to show a mentor's name we join players twice — with two different aliases:
SELECT p.name AS player, m.name AS mentor
FROM players p
JOIN players m ON m.id = p.mentor_id;
The same trick works when one row references the same table twice. A match has a winner and a loser, both players:
SELECT m.id, w.name AS winner, l.name AS loser
FROM matches m
JOIN players w ON w.id = m.winner_id
JOIN players l ON l.id = m.loser_id;
Tip: Each copy of the table needs its own alias, and each alias its own ON condition — mixing them up is the classic self-join bug.
Practice
Each answer runs in your browser and is checked on hidden data.
- Fill in the blanks: For every player who has a mentor, return
player(their name) andmentor(the mentor's name). Row order does not matter. - Write the query: For every match, return its
id, thewinner's name and theloser's name. Row order does not matter. - Find the bug: An upset is a match won by a player with a lower level than the loser. Return the
idof every upset. Row order does not matter.
Previous: Keeping unmatched rows: LEFT JOIN · Next: Joins with aggregates · All lessons