TopicsCheat sheetLessons
Lurndo › Topics › Self join

Learn SQL: Self join

Joining a table to itself

De Kraaien run a mentoring scheme: every youth player can get a mentor from the first teams. "Who mentors whom?" asks Yasmine. Players and mentors are in the same table.

A key to the same table

In players there's a mentor_id. It doesn't point at another table, but at the id of another player in the same table.

Lars Willems has mentor_id 4. Player 4 is Yannick Diallo, the Men A striker.

SELECT id, name, mentor_id FROM players WHERE mentor_id IS NOT NULL
Result
idnamementor_id
9Lars Willems4
10Mila Jacobs6
11Senne Vermeulen2
12Amir Benali7
13Lena Michiels5
14Finn Coppens3
15Noah Lemmens4
SELECT id, name FROM players WHERE team_id IN (4, 5)
The first teams
idname
1Jonas Verhoeven
2Wout Hermans
3Bram De Smet
4Yannick Diallo
5Elke Van Dyck
6Nora Aerts
7Charlotte Maes
8Ines Goossens

The same table twice

For a self join you put the same table in your query twice, with two different aliases. p is the player, m the mentor. To the database they're just two tables that happen to have the same rows.

The ON links the player's mentor_id to the mentor's id.

SELECT p.name AS player, m.name AS mentor FROM players p JOIN players m ON p.mentor_id = m.id
Result
playermentor
Lars WillemsYannick Diallo
Mila JacobsNora Aerts
Senne VermeulenWout Hermans
Amir BenaliCharlotte Maes
Lena MichielsElke Van Dyck
Finn CoppensBram De Smet
Noah LemmensYannick Diallo

Try it yourself

Show every youth player with a mentor. Show the player's name, and the mentor's name and position.

Ready for more?

The full lesson has 7 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousMore than two tablesNext →Working with text
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands