Skip to content
Bronze 5 min read · Joins 1 practice problem ↓

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

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:

Spark SQL · Who referred whom

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05nullNULL: 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 →
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
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:

Spark SQL · Referrals per customer

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05null
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
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?

Spark SQL · Compare a column across the pair

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05null
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
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

ab
AshaAsha
AshaKabir
KabirAsha
KabirKabir

ON ... AND a.id < b.id

ab
AshaKabir

Two Pune customers give four pairs with an equality join, and one with a.customer_id < b.customer_id.

Spark SQL · Customers who live in the same city

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05null
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
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:

Spark SQL · Every earlier order with every later one

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-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: c and r, e and m.
  • 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.id to 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."

A self join with two aliases and a LEFT JOIN: 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?"
Join the table to itself twice, with three aliases for three roles: employee, manager, and the manager's manager, each step joining one level's manager_id to the next level's id. Use LEFT JOINs so people near the top, with no manager or no grand-manager, stay in the result. For a chain of any depth you need a recursive CTE.
Scenario"A table of flights has origin and destination. List every route with exactly one stop."
Join flights to itself where the first flight's destination is the second's origin: 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."
With 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 questions

Why 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 read
Window 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

Previous: Semi and anti joins

Primary sources: JOIN · Date functions (datediff)