SQL · Module 7 · Lesson 51 min read

SELF JOIN

What is a self join?

Joining a table to itself, using two different aliases so SQL treats it as two copies.

CSS
SELECT u.name AS user, r.name AS referred_by
FROM users u
LEFT JOIN users r ON r.id = u.referred_by;

It's not a special keyword — just a normal INNER/LEFT JOIN where both sides are the same table.

When do you need it?

1. Hierarchies (self-referencing FK)

  • Employee → manager
  • User → who referred them (users.referred_by)
  • Category → parent category (categories.parent_id)
  • Comment → parent comment

For unlimited depth (manager of manager of …) use a recursive CTE (Unit 8).

2. Comparing rows within the same table

  • Pairs of users in the same city
  • Expenses by the same user on the same day
  • Products cheaper than another product in the same category

To avoid matching a row with itself and duplicate pairs (A–B and B–A), use a.id < b.id.

3. Comparing to previous/next rows

"Each expense compared with the user's previous one" — possible with a self join, but window functions (LAG/LEAD, Unit 9) are much simpler and faster.

Aliases are mandatory

Without two different aliases, SQL can't tell which copy you mean. Choose meaningful names: u (user) and r (referrer), child and parent, a and b.

Example

SQL
-- Who referred whom? (LEFT JOIN keeps users with no referrer)
SELECT u.name                           AS user_name,
       COALESCE(r.name, '— joined directly —') AS referred_by
FROM users u
LEFT JOIN users r ON r.id = u.referred_by
ORDER BY u.id;
-- Asha Sharma   | — joined directly —
-- Ravi Thapa    | Asha Sharma
-- Sita Gurung   | Asha Sharma
-- Bikash Rai    | Ravi Thapa
-- Maya Karki    | Sita Gurung
-- Hari Shrestha | — joined directly —

-- How many people did each user refer?
SELECT r.name, count(u.id) AS referrals
FROM users r
LEFT JOIN users u ON u.referred_by = r.id
GROUP BY r.id
ORDER BY referrals DESC, r.name
LIMIT 3;
-- Asha Sharma 2, Ravi Thapa 1, Sita Gurung 1

-- Sub-categories with their parent
SELECT child.name AS category, parent.name AS parent
FROM categories child
JOIN categories parent ON parent.id = child.parent_id;
-- Groceries → Food, Restaurants → Food, Electricity → Bills, Internet → Bills

-- Pairs of users in the same city (each pair once)
SELECT a.name AS person_1, b.name AS person_2, a.city
FROM users a
JOIN users b ON a.city = b.city AND a.id < b.id;
-- Asha & Sita (Kathmandu), Ravi & Maya (Pokhara)