Skip to content
Justice Tech School

Self Join

A self join compares rows of the same table, so you need two different aliases. In our data, students.referred_by holds the id of the student who recommended them.

Example
SELECT s.name AS student, r.name AS referred_by
FROM students AS s
JOIN students AS r ON r.id = s.referred_by
ORDER BY s.id;

Result

student | referred_by
Kofi    | Ada
Amina   | Ada
Wanjiru | Kofi
Tunde   | Amina
Zainab  | Ada
Sipho   | Wanjiru
Esi     | Kofi

Exercise

Add the join condition keyword.

SELECT * FROM students s JOIN students r  r.id = s.referred_by;

Quiz Test

Why does a self join need aliases?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.