SELF JOIN for Hierarchical & Peer Comparisons
Join a table to itself for managers, peers, and consecutive-row comparisons.
In plain words
You treat one table as if it were two, give each copy a name, and match rows between them.
Think of it like…
Holding two printouts of the same staff list side by side: on the left you read each employee, on the right you look up their manager's line on the same list.
Where you’ve seen it
An org-chart report shows each employee next to 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 CEO, who has no manager.
Words you’ll hear
- Alias
- A name for each copy of the table (e for employee, m for manager). Required in a self join.
- Self-referencing key
- A column such as manager_id that points at another row's id in the same table.
- Peer comparison
- Comparing a row with other rows that share an attribute, such as the same department.
- Recursive CTE
- What you need instead when the hierarchy has an unknown number of levels.
Visual diagram
Theory & example queries
Hierarchies: employee and manager
When a table stores a parent pointer (manager_id, parent_category_id), a self join puts each row next to its parent. Alias one copy as the child and one as the parent, and join child.parent_id to parent.id.
Use LEFT JOIN if rows at the top of the hierarchy should appear, since they have no parent. Each extra level (grand-manager) needs another self join, so for arbitrary depth switch to a recursive CTE.
SELECT e.nameFROM employees e JOIN employees m ON m.id = e.manager_idWHERE e.salary > m.salary;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Employees above their manager2 sample rows
| name |
|---|
| Priya |
| Omar |
Note: Representative employee-manager pairs from a sample hierarchy.
Key takeaway: Alias the child and the parent, and join child.parent_id = parent.id.
Peer and pair comparisons
Self joins also compare rows that share an attribute: products in the same category, or customers in the same city. Join on the shared column and exclude the row matching itself with a.id <> b.id.
That produces each pair twice (A with B and B with A). Use a.id < b.id to keep each pair once. For "compare with the previous row" in a time series, LAG() is usually simpler and faster than a self join.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
SELECT a.name, b.name, a.cityFROM customers a JOIN customers b ON b.city = a.city AND a.id < b.id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Unique customer pairs by city2 sample rows
| a.name | b.name | city |
|---|---|---|
| Asha | Kabir | Pune |
| Mei | Noah | Seattle |
Note: Rows are illustrative; the id comparison emits each unordered pair once.
Key takeaway: Use a.id < b.id to avoid self-matches and duplicate pairs.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Name the two roles
Decide what each copy represents (employee and manager, or product A and product B) and give each a clear alias.
FROM employees e … employees mWhen to use it & trade-offs
What it is
A self join joins a table to itself, using two different aliases so each copy plays a different role. It's how you compare rows within one table: an employee with their manager, a product with other products in the same category, or a reading with the one before it.
Why it matters: Hierarchies (manager_id pointing at another row's id) and peer comparisons live in a single table, so a normal join to another table can't answer them. "Employees who earn more than their manager" is a classic interview question built on exactly this.
When to reach for it
- Showing each employee with their manager
- Finding employees who earn more than their manager
- Comparing items that share a category, city or other attribute
When to avoid or be careful
- Chaining many self joins to walk a deep hierarchy; use a recursive CTE
- Self joins for previous-row comparisons in time series; LAG() is simpler
- Peer joins without a.id < b.id, which double the pairs and match rows with themselves
Self join vs LAG() vs recursive CTE
Strengths: Works in every SQL database and reads clearly.
Watch out: One join per level, and pair comparisons can produce many rows.
Strengths: One pass over the data, no join.
Watch out: Only works for neighbours in a sort order, not arbitrary pairs.
Strengths: Walks any number of levels.
Watch out: More complex, and you must guard against cycles.
Interview signals & numbers to know
When this topic comes up
- “Employees who earn more than their managers”
- manager_id or parent_id columns
- “Find pairs of …”
- “Compare each row with others in the same group”
- Org chart
Benchmarks & rules of thumb
- 2
- aliases for the same table
- a.id < b.id
- each pair once
- 1 join
- per hierarchy level
Common mistakes & follow-ups
Common interview mistakes
- Forgetting aliases, so the database reports ambiguous columns or you compare a row with itself.
- Using INNER JOIN for the manager lookup and losing the employees who have no manager.
- Joining peers with a.id <> b.id and reporting every pair twice.
Likely interviewer follow-ups
- How would you list each employee with their manager's manager?
- How would you return the whole management chain above an employee?
- When would you use LAG() instead of a self join?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply SELF JOIN for Hierarchical & Peer Comparisons with hands-on SQL practice and interview Q&A.