Self joins
Sometimes the row you need to compare with is in the same table: the customer who referred another customer, the previous order of the same person. A self join joins a table to itself to reach it. This lesson shows how, and the one thing that makes it work: giving each copy its own name.
Foundations · SQL for data engineers · Bronze · Joining tables, lesson 3 of 3
On this page
Read first: Inner and outer joins (skip if you know it)
In plain words first
A school's student list has a column "buddy", holding another student's id. To print each student next to their buddy's name, you need to look in the same list twice: once for the student, once for the buddy. So you photocopy the list, label one copy "student" and the other "buddy", and match them up.
That is a self join: the same table used twice, each copy with its own aliasalias: A short name given with AS (or just a space) to a table or column, like orders o or amount + 25 AS total. Learn more → so SQL knows which one you mean.
Two copies of one table
A self join is an ordinary join where both sides are the same table. The only new thing is that you must give each side its own alias, because every column name now exists twice. Think of it as two copies of the table with different roles: in the first example below, c is the customer and r is the customer who referred them.
Looking up a related row
Each customer row stores referred_by, the id of another customer. To show the referrer's name, join customers to itself on that id:
Input: customers
| customer_id | name | city | signup_date | referred_by |
|---|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 | nullNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → |
| 2 | Ravi | Delhi | 2026-01-20 | 1 |
| 3 | Meera | null | 2026-02-02 | 1 |
| 4 | Kabir | Pune | 2026-02-14 | 2 |
| 5 | Zoya | Mumbai | 2026-03-01 | null |
SELECT c.name, r.name AS referred_by FROM customers c LEFT JOIN customers r ON c.referred_by = r.customer_id ORDER BY c.customer_id
A LEFT JOIN keeps Asha and Zoya, whom nobody referred. With an inner join they would disappear. The same shape answers every "row points to another row of the same table" question: employee and manager, category and parent category, flight and connecting flight.
Once the pairs exist, you can aggregateaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → them like any join:
Input: customers
| customer_id | name | city | signup_date | referred_by |
|---|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 | null |
| 2 | Ravi | Delhi | 2026-01-20 | 1 |
| 3 | Meera | null | 2026-02-02 | 1 |
| 4 | Kabir | Pune | 2026-02-14 | 2 |
| 5 | Zoya | Mumbai | 2026-03-01 | null |
SELECT r.name, count(*) AS referrals FROM customers c JOIN customers r ON c.referred_by = r.customer_id GROUP BY r.name ORDER BY referrals DESC, r.name
Comparing a row with a related row
With both rows side by side, you can compare their columns. Which customers signed up within 20 days of the person who referred them?
Input: customers
| customer_id | name | city | signup_date | referred_by |
|---|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 | null |
| 2 | Ravi | Delhi | 2026-01-20 | 1 |
| 3 | Meera | null | 2026-02-02 | 1 |
| 4 | Kabir | Pune | 2026-02-14 | 2 |
| 5 | Zoya | Mumbai | 2026-03-01 | null |
SELECT c.name, r.name AS referrer, datediff(c.signup_date, r.signup_date) AS days_later FROM customers c JOIN customers r ON c.referred_by = r.customer_id WHERE datediff(c.signup_date, r.signup_date) <= 20
Ravi joined 15 days after Asha. Meera (28 days) and Kabir (25 days) are filtered out.
Pairs without duplicates
Joining a table to itself on a shared value pairs every row with every other row that shares it, including itself, and each pair appears twice (A with B, then B with A). A strict inequality on the key removes both problems:
ON a.city = b.city
| a | b |
|---|---|
| Asha | Asha |
| Asha | Kabir |
| Kabir | Asha |
| Kabir | Kabir |
ON ... AND a.id < b.id
| a | b |
|---|---|
| Asha | Kabir |
Two Pune customers give four pairs with an equality join, and one with a.customer_id < b.customer_id.
Input: customers
| customer_id | name | city | signup_date | referred_by |
|---|---|---|---|---|
| 1 | Asha | Pune | 2026-01-05 | null |
| 2 | Ravi | Delhi | 2026-01-20 | 1 |
| 3 | Meera | null | 2026-02-02 | 1 |
| 4 | Kabir | Pune | 2026-02-14 | 2 |
| 5 | Zoya | Mumbai | 2026-03-01 | null |
SELECT a.name, b.name AS same_city_as, a.city FROM customers a JOIN customers b ON a.city = b.city AND a.customer_id < b.customer_id
Meera has no city, and NULL never equals NULL, so she pairs with nobody. Use <> instead of < when order matters and you want both (A, B) and (B, A).
The same trick finds pairs of orders by the same customer, the earlier one first:
Input: orders
| order_id | customer_id | restaurant | city | amount | status | placed_at |
|---|---|---|---|---|---|---|
| 101 | 1 | Spice Route | Pune | 420 | delivered | 2026-03-01 12:10:00 |
| 102 | 2 | Pizza Lab | Delhi | 650 | cancelled | 2026-03-01 19:40:00 |
| 103 | 1 | Pizza Lab | Pune | null | delivered | 2026-03-02 13:05:00 |
| 104 | 3 | Spice Route | Pune | 310 | null | 2026-03-03 20:15:00 |
| 105 | 2 | Wok Inn | Delhi | 280 | delivered | 2026-03-04 21:00:00 |
| 106 | 4 | Spice Route | Pune | 540 | delivered | 2026-03-05 13:30:00 |
| 107 | 9 | Wok Inn | Mumbai | 190 | delivered | 2026-03-05 20:45:00 |
| 108 | 1 | Wok Inn | Pune | 360 | refunded | 2026-03-06 19:10:00 |
SELECT a.customer_id, a.order_id AS earlier, b.order_id AS later FROM orders a JOIN orders b ON a.customer_id = b.customer_id AND a.placed_at < b.placed_at ORDER BY a.customer_id, earlier, later
When a window function is better
Asha has 3 orders and gets 3 pairs; a customer with 1,000 orders would get about 500,000. A self join with an inequality grows with the square of the group size. If the real question is "compare each order with the previous one", a window function (LAG, in the Silver lessons) reads each row once and is the right tool. Keep self joins for lookups between different rows and for genuine pairs.
Common mistakes
- Forgetting the aliases — Without two aliases every column is ambiguous. Name the roles:
candr,eandm. - Joining on = alone when building pairs — Each row pairs with itself and every pair appears twice. Add
a.id < b.id. - Using an inner join for an optional parent — Rows without a referrer or manager disappear. Use a LEFT JOIN to keep them.
- Self-joining to get the previous row — An inequality self join grows with the square of the group. Use LAG or LEAD for neighbours.
Key takeaways
- A self join is a normal join of a table with itself; two aliases give the two roles.
- Use a LEFT JOIN when the related row is optional.
- Build pairs with
a.id < b.idto avoid self-pairs and duplicates. - For the previous or next row, LAG and LEAD beat a self join.
Interview prep
THE QUESTION
"The customers table has a referred_by column holding another customer's id. List every customer with the name of whoever referred them, including customers nobody referred."
SELECT c.name, r.name AS referred_by FROM customers c LEFT JOIN customers r ON c.referred_by = r.customer_id. The LEFT JOIN keeps customers whose referred_by is NULL, with a NULL referrer. Mention that the same pattern handles employee and manager, and that following the chain more than one level up needs a recursive CTE or repeated joins.Avoid: "JOIN customers r ON c.referred_by = r.customer_id." Correct pairs, but an inner join drops every customer nobody referred, and the question asked for them.
Follow-ups · answer out loud, then open
Follow-up"Each employee row has a manager_id. How do you show each employee's manager and the manager's manager?"
Scenario"A table of flights has origin and destination. List every route with exactly one stop."
FROM flights a JOIN flights b ON a.dest = b.origin AND b.dep_time > a.arr_time, and exclude routes that return to the start (b.dest <> a.origin). Add a minimum connection time if needed.Trap"To find duplicate customer rows, self join on email and keep the pairs."
ON a.email = b.email alone, every row matches itself, so every customer looks duplicated, and each real pair appears twice. Add AND a.customer_id < b.customer_id. Often GROUP BY email HAVING count(*) > 1 is simpler and cheaper.Check yourself
4 questionsWhy must a self join use aliases?
Show the answer
Every column name exists twice. Both sides are the same table, so names are ambiguous without aliases.
Three customers share a city. How many rows does ON a.city = b.city AND a.id < b.id give?
Show the answer
3. Three unordered pairs: (1,2), (1,3) and (2,3).
And with ON a.city = b.city alone?
Show the answer
9. Every row pairs with all three, itself included: 3 × 3.
Which tool fits "compare each order with the customer's previous order"?
Show the answer
LAG(). A window function reads each row once instead of building every pair.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · new module: Window functions · 7 min readWindow functions: ranking and top N
Keep every row while computing over a group, number rows with ROW_NUMBER, RANK and DENSE_RANK, and get the top N per group.
Related lessons
Inner and outer joinsSQL for data engineers · 7 min read
Semi and anti joinsSQL for data engineers · 6 min read
GROUP BY and HAVING
Previous: Semi and anti joins
Primary sources: JOIN · Date functions (datediff)