Self Join

Updated · 7 min read
mediumPostgreSQL 18sqlself-joinjoinshierarchyinterview

A self join joins a table to itself, using two aliases so the same table can play two roles. It isn't a new kind of join; it's an ordinary inner or left join where both sides happen to be the same table. You need one whenever a row points to another row in its own table. In the Fee Tracker, each student's mentor_id is another student's id, so "who mentors whom?" needs students twice: once as the student, once as the mentor. This lesson follows the mentor chain, shows each course's prerequisite, and uses self joins to compare rows in the same table.

In One Minute

  • A self join lists the same table twice with different aliases: students AS s, students AS m.
  • Each alias is a separate copy for the query; ON m.student_id = s.mentor_id connects them.
  • Use LEFT JOIN so rows with no partner, like a student without a mentor, still appear.
  • Join a third copy to go one level further up a chain.
  • To compare rows, add a.id < b.id so each pair appears once, and never with itself.

The Mentor Chain

Give the table two aliases, one per role. Each student, with their mentor's name:

SQL▶ Try it
SELECT s.first_name AS student, m.first_name AS mentor
FROM students AS s
LEFT JOIN students AS m ON m.student_id = s.mentor_id
ORDER BY s.student_id;
Output
 student  |  mentor
----------+----------
 Srihitha | NULL
 Advitha  | Srihitha
 Navika   | Advitha
(3 rows)

Read s as "the student" and m as "the mentor". For Navika, s.mentor_id is 102, which matches the row in m with student_id 102, Advitha. Srihitha has no mentor (mentor_id is NULL), so the LEFT JOIN keeps her with NULL; an inner join would drop her. The aliases are required: with students twice and no aliases, PostgreSQL couldn't tell which copy first_name came from.

Each student's mentor_id is matched to another row of the same table: Advitha is mentored by Srihitha, Navika by Advitha

Going Up the Chain

Each extra copy of the table goes one level further. Mentors' mentors:

SQL▶ Try it
SELECT s.first_name  AS student,
       m.first_name  AS mentor,
       gm.first_name AS mentors_mentor
FROM students AS s
LEFT JOIN students AS m  ON m.student_id  = s.mentor_id
LEFT JOIN students AS gm ON gm.student_id = m.mentor_id
ORDER BY s.student_id;
Output
 student  |  mentor  | mentors_mentor
----------+----------+----------------
 Srihitha | NULL     | NULL
 Advitha  | Srihitha | NULL
 Navika   | Advitha  | Srihitha
(3 rows)

Navika is mentored by Advitha, who is mentored by Srihitha. Each level needs another join, so this only works when you know how deep the chain goes. For chains of any depth, such as an org chart, Recursive CTEs walks the whole tree with one query.

The other direction works too. How many students does each student mentor?

SQL▶ Try it
SELECT m.first_name AS mentor, count(s.student_id) AS mentees
FROM students AS m
LEFT JOIN students AS s ON s.mentor_id = m.student_id
GROUP BY m.student_id, m.first_name
ORDER BY m.student_id;
Output
  mentor  | mentees
----------+---------
 Srihitha |       1
 Advitha  |       1
 Navika   |       0
(3 rows)

Here m is on the left, so every student appears as a possible mentor, and count(s.student_id) counts only real mentees, giving Navika 0.

Course Prerequisites

The same pattern works for any table that points to itself. courses.prerequisite_id points at another course:

SQL▶ Try it
SELECT c.title AS course, pre.title AS prerequisite
FROM courses AS c
LEFT JOIN courses AS pre ON pre.course_id = c.prerequisite_id
ORDER BY c.course_id;
Output
      course       | prerequisite
-------------------+--------------
 Java Basics       | NULL
 Java OOP          | Java Basics
 Java Collections  | Java OOP
 SQL Basics        | NULL
 JavaScript Basics | NULL
 Git Basics        | NULL
(6 rows)

Java OOP needs Java Basics, and Java Collections needs Java OOP: a three-step chain. The other courses have no prerequisite.

Java Basics, then Java OOP, then Java Collections, read from courses joined to itself

Comparing Rows in the Same Table

A self join can also pair rows that share a value, such as payments of the same amount:

SQL▶ Try it
SELECT a.payment_id, b.payment_id AS same_amount_as, a.amount_usd
FROM payments AS a
JOIN payments AS b
  ON b.amount_usd = a.amount_usd
 AND a.payment_id < b.payment_id
ORDER BY a.payment_id;
Output
 payment_id | same_amount_as | amount_usd
------------+----------------+------------
          2 |              3 |     250.00
          6 |              7 |     225.00
(2 rows)

Two pairs: payments 2 and 3 are both $250.00, and 6 and 7 are both $225.00. The a.payment_id < b.payment_id condition does two jobs. It stops each payment from pairing with itself (every payment has the same amount as itself), and it keeps each pair once, as (2, 3) and not also as (3, 2). With <> instead of <, you'd get both orders.

Only the cells above the diagonal are kept: each pair once, never a row with itself

Common Mistakes

No aliases. FROM students JOIN students fails: PostgreSQL reports table name "students" specified more than once. Give each copy its own alias.

Joining the wrong direction. ON m.student_id = s.mentor_id finds each student's mentor; ON s.student_id = m.mentor_id finds each student's mentees. Name the aliases by role so it's obvious.

Inner join on a nullable link. Srihitha, with no mentor, disappears. Use LEFT JOIN.

Forgetting a.id < b.id. Every row pairs with itself, and each pair appears twice.

Interview Corner

What is a self join?

A join of a table to itself, using two aliases so each copy can play a different role, such as student and mentor, or employee and manager.

How do you list each employee with their manager's name?

SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON m.id = e.manager_id. The LEFT JOIN keeps the top manager, who has no manager.

How do you find pairs of rows with the same value without duplicates?

Self join on the value and add a.id < b.id, which removes both self-pairs and mirrored pairs.

Practice

Challenge: List pairs of students who live in the same state, each pair once, showing both first names and the state.

Show solution
SQL▶ Try it
SELECT a.first_name, b.first_name AS lives_in_same_state_as, a.state
FROM students AS a
JOIN students AS b
  ON b.state = a.state
 AND a.student_id < b.student_id
ORDER BY a.student_id, b.student_id;
Output
 first_name | lives_in_same_state_as | state
------------+------------------------+-------
 Srihitha   | Advitha                | CA
(1 row)

Srihitha and Advitha both live in California. Navika is the only student in Texas, so she has no pair.

Quick check: Self join

3 questions
1Why does a self join need table aliases?
2Srihitha has no mentor. Which join keeps her in students s ... JOIN students m ON m.student_id = s.mentor_id?
3What does a.payment_id < b.payment_id add to a self join on amount_usd?

Key Takeaways

You want toWrite
Each student's mentorFROM students s LEFT JOIN students m ON m.student_id = s.mentor_id
Each course's prerequisiteFROM courses c LEFT JOIN courses pre ON pre.course_id = c.prerequisite_id
Pairs with the same amountFROM payments a JOIN payments b ON b.amount_usd = a.amount_usd AND a.payment_id < b.payment_id

Was this tutorial helpful?

Lesson 40 of 115