Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 49/ 160
03. Joins & Relational Querying

SELF JOIN for Hierarchical & Peer Comparisons

Join a table to itself for managers, peers, and consecutive-row comparisons.

IntermediateSelf Join · Hierarchy3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Employees who earn more than their managerQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  e.name3FROM4  employees e5  JOIN employees m ON m.id = e.manager_id6WHERE7  e.salary > m.salary;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Employees above their manager2 sample rows
Employees above their manager
name
Priya
Omar

Note: Representative employee-manager pairs from a sample hierarchy.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Pairs of customers in the same city, each pair onceQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  a.name,3  b.name,4  a.city5FROM6  customers a7  JOIN customers b ON b.city = a.city8  AND a.id < b.id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Unique customer pairs by city2 sample rows
Unique customer pairs by city
a.nameb.namecity
AshaKabirPune
MeiNoahSeattle

Note: Rows are illustrative; the id comparison emits each unordered pair once.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use a.id < b.id to avoid self-matches and duplicate pairs.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Name the two roles

Decide what each copy represents (employee and manager, or product A and product B) and give each a clear alias.

SQL at this stepReadable preview
1FROM employees e … employees m
What to watch at this step
Aliases
required
Tip: use ← → to move between steps

When 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

Self join
Best for: One level of hierarchy, or comparing pairs of rows

Strengths: Works in every SQL database and reads clearly.

Watch out: One join per level, and pair comparisons can produce many rows.

LAG() / LEAD()
Best for: Comparing each row with the previous or next row in an order

Strengths: One pass over the data, no join.

Watch out: Only works for neighbours in a sort order, not arbitrary pairs.

Recursive CTE
Best for: Hierarchies of unknown depth (full org chart, category tree)

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?
Interview tip: Say out loud which copy is which ("e is the employee, m is their manager") before writing the ON clause. It avoids the most common self-join bug: joining the keys the wrong way round.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
CROSS JOIN (Cartesian Products & Use Cases)
Next topic
Non-Equi Joins (Joining on Ranges, Dates & Inequalities)