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_id | first_name | last_name | department | salary | hire_date | manager_id |
|---|---|---|---|---|---|---|
| 1 | Karen | Mitchell | Management | 93600 | 2018-01-02 | NULL |
| 2 | Tom | Bradley | Sales | 62400 | 2019-04-01 | 1 |
| 3 | Julia | Reyes | Sales | 46800 | 2021-06-15 | 2 |
| 4 | Marcus | Allen | Sales | 49200 | 2020-09-01 | 2 |
| 5 | Sarah | Long | Warehouse | 39600 | 2022-02-01 | 1 |
| 6 | Felix | Turner | Warehouse | 35400 | 2024-03-18 | 5 |
| 7 | Nina | Cooper | Accounting | 52800 | 2019-10-01 | 1 |
| 8 | David | Ross | Customer service | 38400 | 2023-05-02 | 2 |
| 9 | Laura | Hughes | Customer service | NULL | 2025-09-01 | 2 |
| 10 | Paul | Ward | Accounting | 43200 | 2022-11-14 | 7 |
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_name | last_name | boss_first | boss_last |
|---|---|---|---|
| Tom | Bradley | Karen | Mitchell |
| Julia | Reyes | Tom | Bradley |
| Marcus | Allen | Tom | Bradley |
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_namerefers to. With aliases you prefix every column:e.last_nameis the employee,m.last_namethe manager. - Direction matters.
e.manager_id = m.employee_idmeans 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_id | first_name | last_name | department | salary | hire_date | manager_id |
|---|---|---|---|---|---|---|
| 1 | Karen | Mitchell | Management | 93600 | 2018-01-02 | NULL |
| 2 | Tom | Bradley | Sales | 62400 | 2019-04-01 | 1 |
| 3 | Julia | Reyes | Sales | 46800 | 2021-06-15 | 2 |
| 4 | Marcus | Allen | Sales | 49200 | 2020-09-01 | 2 |
| 5 | Sarah | Long | Warehouse | 39600 | 2022-02-01 | 1 |
| 6 | Felix | Turner | Warehouse | 35400 | 2024-03-18 | 5 |
| 7 | Nina | Cooper | Accounting | 52800 | 2019-10-01 | 1 |
| 8 | David | Ross | Customer service | 38400 | 2023-05-02 | 2 |
| 9 | Laura | Hughes | Customer service | NULL | 2025-09-01 | 2 |
| 10 | Paul | Ward | Accounting | 43200 | 2022-11-14 | 7 |
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';
| name | name | city |
|---|---|---|
| Harbor Fremont Partners | Chloe Evans | Boston |
| Harbor Fremont Partners | Harbor Fremont Partners | Boston |
| Chloe Evans | Chloe Evans | Boston |
| Chloe Evans | Harbor Fremont Partners | Boston |
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_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-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:
| Database | Recursive query over a hierarchy |
|---|---|
| MySQL | WITH RECURSIVE is required as soon as a CTE refers to itself. |
| PostgreSQL | WITH RECURSIVE; without RECURSIVE a WITH query can't refer to its own output. |
| SQL Server | Plain WITH; there is no RECURSIVE keyword. By default the query stops after 100 levels, adjustable with OPTION (MAXRECURSION n). |
| SQLite | Accepts 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.