SQL Tutorial 0/85 lessons ~6 min read Lesson 40
SELF JOIN
A self join joins a table to itself.
Course progress0%
Focus
6 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
A self join joins a table to itself. Used for hierarchies (employee → manager), pairs of related rows (find duplicates) or comparing rows in the same table.
Understanding the topic
Core concepts to understand:
FROM employees e JOIN employees m ON e.manager_id = m.id.- Use distinct aliases for the two copies.
- Common in org charts, threaded comments.
- Find duplicates:
FROM t a JOIN t b ON a.email=b.email AND a.id<b.id. - Recursive CTE often a cleaner alternative for hierarchies.
Syntax reference
Visual workflow / architecture:
bash
employees employeese (worker) → m (manager)id manager_id id name1 NULL NULL2 1 1 CEO3 1 1 CEO4 2 2 CTO
Syntax Pattern
SELECT <cols>
FROM <t> AS a
JOIN <t> AS b
ON <a.col> = <b.related_col>;SELF JOINJoins a table to itself — use two distinct aliases.aliasesTreat each copy as a separate logical table.
Live Example
sql
SELECT e.name AS worker, m.name AS managerFROM employees eJOIN employees m ON e.manager_id = m.id;
employees
| id | name | manager_id |
|---|---|---|
| 1 | Ada (CEO) | NULL |
| 2 | Leo | 1 |
| 3 | Mia | 1 |
| 4 | Rio | 2 |
runs
worker → manager
| worker | manager |
|---|---|
| Leo | Ada (CEO) |
| Mia | Ada (CEO) |
| Rio | Leo |
Perfect for org charts, threaded comments, and finding duplicate rows.
Real-world use
Org-chart pages, 'find duplicate emails' admin queries, and threaded forum replies all use self-joins.
Best practices
- Use clear aliases (
e,m). - Consider recursive CTEs for deep hierarchies.
- Index the join column on both sides (it's the same column!).
Hands-on exercise
Interview preparation — practice these questions:
- Q1. Why use a self join?
- Q2. Find duplicate emails query.
- Q3. Self join vs recursive CTE.
- Q4. Aliasing rules.
- Q5. Org-chart query example.
Ready to mark this lesson complete?Track your journey across the entire course.