Self Joins and Hierarchies: Employees and Managers

SQL Interview Problems: 12 Classic Questions Solved · Missing Rows and Relationships · 6 min read · Updated

A table joined to itself

  1. Picture the same table twice. One copy plays the employee, the other plays the manager.
  2. The join condition links the employee manager_id to the manager id.
  3. Now one row holds both the employee and the manager side by side.
  4. You can compare them, for example employee salary against manager salary.

Almost every company has a table where one column points to another row of the same table: an employee has a manager, and the manager is also an employee. A self join is how you ask questions across that link. It is a favourite interview topic because the idea is simple but the first attempt confuses many people. The trick is to remember that you are using the same table twice, so you must give it two different aliases and think of them as two separate tables.

Employees with their manager's name

In our employees table, manager_id holds the id of the manager. Imagine two copies of the table. Copy e is the employee. Copy m is the manager. The join condition connects the employee's manager_id to the manager's id.

SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
ORDER BY e.id;
employee    | manager
Meera Joshi | NULL
Arjun Rao   | Meera Joshi
Sara Khan   | Meera Joshi
Liam Brown  | Arjun Rao
Nia Okoye   | Arjun Rao
Omar Ali    | Meera Joshi
Priya Nair  | Omar Ali
Tom Hill    | Omar Ali
Zoe Park    | Omar Ali
Ravi Menon  | Meera Joshi
Ella Stone  | Ravi Menon
Dev Patel   | Meera Joshi
Chloe Wu    | Dev Patel
Jack Reed   | Dev Patel

We used LEFT JOIN on purpose. Meera Joshi has no manager, her manager_id is NULL, and an inner join would drop her from the list. With the left join she stays, and her manager shows as NULL. If the question says "list all employees with their manager", the left join is the correct answer.

Who earns more than their manager?

This classic question follows directly. Join each employee to their manager and compare the two salaries.

SELECT e.name AS employee, e.salary,
       m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
employee  | salary | manager   | manager_salary
Nia Okoye | 130000 | Arjun Rao | 120000

Nia Okoye earns 130000, and her manager Arjun Rao earns 120000. Here an inner join is right, because someone without a manager cannot earn more than their manager. People with a NULL salary are also left out, since a comparison with NULL is never true.

Managers with many direct reports

Group by the manager and count the people who report to them. HAVING keeps only the managers with at least three.

SELECT m.name, COUNT(*) AS direct_reports
FROM employees e
JOIN employees m ON m.id = e.manager_id
GROUP BY m.id
HAVING COUNT(*) >= 3
ORDER BY direct_reports DESC;
name        | direct_reports
Meera Joshi | 5
Omar Ali    | 3

Meera has five direct reports and Omar has three. Notice that we grouped by m.id, the manager, and selected m.name. That is safe because the name depends only on the id. Some databases still require you to write both columns in GROUP BY, so if you get an error add m.name to the clause.

The whole org chart with a recursive query

A self join only goes one level. "Show everyone under the CEO, with how many levels down they are" needs a loop. SQL does this with a recursive common table expression. It has two parts joined by UNION ALL. The first part is the starting point: the person with no manager. The second part repeats: find the people whose manager is in the result so far, and add one to the depth. It stops when no new people are found.

WITH RECURSIVE chain AS (
  SELECT id, name, 0 AS depth
  FROM employees
  WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, c.depth + 1
  FROM employees e
  JOIN chain c ON e.manager_id = c.id
)
SELECT depth, name
FROM chain
ORDER BY depth, name;
depth | name
0     | Meera Joshi
1     | Arjun Rao
1     | Dev Patel
1     | Omar Ali
1     | Ravi Menon
1     | Sara Khan
2     | Chloe Wu
2     | Ella Stone
2     | Jack Reed
2     | Liam Brown
2     | Nia Okoye
2     | Priya Nair
2     | Tom Hill
2     | Zoe Park

Meera is at depth 0, five people report to her at depth 1, and the remaining eight are at depth 2. You do not need to remember the syntax perfectly. You do need to explain the two parts: a starting row, and a rule that finds the next level. In PostgreSQL, MySQL 8 and SQL Server this feature exists, and SQL Server writes it without the word RECURSIVE.

Common mistakes

  • Forgetting the aliases, so the database cannot tell which copy of the table a column belongs to.
  • Joining on the wrong pair, e.id = m.manager_id, which finds a person's reports instead of their manager.
  • Using an inner join when the question wants everyone, and losing the top person.
  • Comparing salaries when one is NULL and expecting an answer.

Your task

  1. List each employee with their manager's name and the manager's salary.
  2. Find all employees who earn exactly the same as their manager (there may be none, and say so).
  3. Find the managers who have exactly two direct reports.
  4. Change the recursive query to start at Omar Ali (id 6) and show his team with the depth.

How to check it worked

  • Only Nia Okoye earns more than her manager.
  • Meera Joshi shows NULL as her manager, and 14 rows come back from the manager list.
  • The recursive query returns 14 rows, with depths 0, 1 and 2.

Frequently asked questions

Why do I need two different aliases?

Both copies have the same column names. The aliases tell the database and the reader which copy a column comes from.

Should I use an inner join or a left join?

Use a left join when people without a match, such as the top manager, must still appear. Use an inner join when only matched pairs matter.

What is a recursive query used for besides org charts?

Category trees, folders, bills of materials and any data where a row points to a parent row of the same table.