SQL self join: joining a table to itself

Sometimes the answer lives in the same table as the question. An employee's manager is also an employee; a customer in the same city is also a customer. A self join uses the table twice and lines up the rows that belong together.

In short: FROM employees e JOIN employees m ON e.manager_id = m.employee_id pairs each employee (e) with their manager (m). A self join is an ordinary join with the same table on both sides, so each side needs its own alias.

What you should know first: joining tables with INNER JOIN and LEFT JOIN.

Try it now

In the employees table, manager_id holds the employee_id of each person's boss. To turn that number into a name, you have to look in the same table a second time.

Task For the new org chart, HR needs each person's direct manager. From the employees table, show the person's first_name and last_name, then the last_name of their manager, in that order. The manager is stored in manager_id. Leave out anyone who has no manager.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

How a self join works

Picture printing the staff list twice. Label one copy "employee" and the other "manager". For each row on the first copy, find the row on the second copy whose employee_id equals the manager_id, and lay the two side by side. That's exactly what SQL does when you name the same table twice under different aliases:

SELECT e.first_name, e.last_name,
       m.first_name AS boss_first, m.last_name AS boss_last
FROM employees AS e
JOIN employees AS m ON e.manager_id = m.employee_id
WHERE e.department = 'Sales';
first_namelast_nameboss_firstboss_last
TomBradleyKarenMitchell
JuliaReyesTomBradley
MarcusAllenTomBradley

Tom Bradley plays two parts here: an employee in the first row and the boss in the other two. That's the whole idea of a self join. The same row can sit on the left in one role and on the right in another.

  • Aliases are required. Without e and m, SQL can't tell which copy last_name refers to. With aliases you prefix every column: e.last_name is the employee, m.last_name the manager.
  • Direction matters. e.manager_id = m.employee_id means the employee points to their boss. Flip it and you get each boss with their direct reports.
  • Name the columns. Otherwise the result has two columns called last_name. AS gives the manager's columns names of their own.

One more exercise: don't lose the CEO

Karen Mitchell runs the company and reports to nobody. An inner join finds no match for her and drops her row. For a complete list you need LEFT JOIN: the employee sits on the left and always stays, and the manager columns are simply NULL for her.

Task Now the complete list for the phone system: every employee with last_name and department, followed by their manager's last_name, in that order. The CEO must appear too, even though she has no manager; her third column stays empty.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Finding pairs within one table

A self join doesn't have to follow a key like manager_id. You can also match on a shared value, such as the city. Try just ON a.city = b.city for Boston:

SELECT a.name, b.name, a.city
FROM customers a
JOIN customers b ON a.city = b.city
WHERE a.city = 'Boston';
namenamecity
Harbor Fremont PartnersChloe EvansBoston
Harbor Fremont PartnersHarbor Fremont PartnersBoston
Chloe EvansChloe EvansBoston
Chloe EvansHarbor Fremont PartnersBoston

Two Boston customers turn into four rows: each one is paired with itself, and the real pair appears twice. A second condition fixes both problems: a.customer_id < b.customer_id. Equal IDs drop out, and only one of the two directions survives.

Task The field sales team wants to combine visits and is looking for customers based in the same city. Build pairs from the customers table: name of the first customer, name of the second customer and their shared city, in that order. Each pair should appear only once, with the customer that has the lower customer_id first. Nobody is paired with themselves.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

No aliases

FROM employees JOIN employees ON manager_id = employee_id can't work, because every column now exists twice. The exercise reports: "The column "first_name" exists in more than one table." Putting the table name in front doesn't help this time, since both sides are called employees. Give each side its own alias.

Join condition the wrong way round

With ON e.employee_id = m.manager_id the roles swap: e becomes the boss and m the employee. The row count often still matches. The exercise spots the swap and says "The direction of your self join is reversed". Read the condition aloud: "the employee's manager_id is the manager's employee_id."

JOIN where you needed LEFT JOIN

If every employee should appear, an inner join loses the one without a manager: "Your query returns only 9 rows. Wanted: 10 rows." When a hierarchy is one row short, the missing row is almost always the person at the top.

Duplicate pairs

a.customer_id <> b.customer_id only removes the self-pairs. A with B and B with A both stay, so you get twice as many rows as wanted. Use < instead of <>.

Comma instead of JOIN

FROM customers a, customers b WHERE … returns the same rows, but it's the older style. The exercises in this lesson ask for JOIN … ON, which keeps the link between the tables separate from the filter.

Self joins in MySQL, PostgreSQL, SQL Server and SQLite

A self join works the same in all four. There's no special keyword for it; you write JOIN or LEFT JOIN with two aliases. Microsoft's documentation of the FROM clause even names the self join as a reason to use a table alias.

One self join covers exactly one level. For a manager's manager you add another self join. To walk a hierarchy of any depth you need a recursive CTE (WITH, level 5), and that's where the databases differ:

DatabaseRecursive query over a hierarchy
MySQLWITH RECURSIVE is required as soon as a CTE refers to itself.
PostgreSQLWITH RECURSIVE; without RECURSIVE a WITH query can't refer to its own output.
SQL ServerPlain WITH; there is no RECURSIVE keyword. By default the query stops after 100 levels, adjustable with OPTION (MAXRECURSION n).
SQLiteAccepts WITH RECURSIVE and, for compatibility with SQL Server and Oracle, plain WITH as well.

FAQ

What is a self join in SQL?

A join with the same table on the left and the right. Classic uses are hierarchies (employees and managers, categories and parent categories) and comparisons within one table, such as customers in the same city or orders from the same customer.

How do I get the manager's manager?

Add a second self join: JOIN employees mm ON m.manager_id = mm.employee_id. For Julia Reyes that returns Bradley as her manager and Mitchell as his. Anyone whose manager has no manager drops out with JOIN and stays with LEFT JOIN.

How many people report to each manager?

Self join plus GROUP BY on the manager: SELECT m.last_name, COUNT(*) FROM employees e JOIN employees m ON e.manager_id = m.employee_id GROUP BY m.employee_id, m.last_name. In the practice shop, Bradley has four direct reports, Mitchell three, Long and Cooper one each.

Do I have to write AS before the alias?

No. employees e and employees AS e mean the same thing, and you'll see both in real code. What matters is that the two copies get different names.

Up next: UNION

A join puts columns side by side. UNION stacks the rows of two queries on top of each other, such as customers and employees in one shared list. You'll also see when UNION removes duplicates and when it doesn't.

Practice UNION

Write to us

Choose language

Select your preferred language