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.

Previous: Keeping unmatched rows: LEFT JOIN · Next: Joins with aggregates · All lessons