Employees Without a Manager
Return every employee's name and their manager's name as
manager. Employees with no manager must still appear, with
NULL for manager.
Order by employee name.
Expected output
name | manager
------+--------
Alice | NULL
Bob | Alice
Carol | Alice
Dan | Carol
Erin | Carol
Frank | Erin
Editorial
A self-join: the same table on both sides of the join, distinguished by alias.
SELECT e.name, m.name AS manager
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
ORDER BY e.name;
e is the employee, m is the manager. They are the
same table read twice, and the aliases are not optional — without them every
column reference is ambiguous.
Why LEFT and not INNER
Alice's manager_id is NULL, so there is no row in m
to pair her with. An INNER JOIN returns five rows and silently
drops the one person at the top of the organisation:
-- five rows, no Alice
SELECT e.name, m.name AS manager
FROM employee e
JOIN employee m ON m.id = e.manager_id
ORDER BY e.name;
That is the whole lesson of this problem. A self-join on a nullable column
needs LEFT, and the row it would drop is usually the most
significant one — the root, the first record, the one without a parent.
Showing something instead of NULL
SELECT e.name, coalesce(m.name, '— none —') AS manager
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
ORDER BY e.name;
Reasonable for a report. Note it changes the type of answer: a reader can no
longer distinguish "no manager" from an employee literally named
— none —. For an API response, keep the NULL.
What this does not do
One join gives one level. Frank reports to Erin who reports to Carol, and nothing above reveals that Carol is Frank's skip-level manager. A full hierarchy needs a recursive CTE:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS depth
FROM employee WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employee e JOIN chain c ON c.id = e.manager_id
)
SELECT name, depth FROM chain ORDER BY depth, name;
Worth recognising, and worth knowing it is the point where a relational database starts to be the wrong tool — unbounded-depth traversal is what graph databases make the primitive.
What an interviewer is checking
That you alias both sides, and that you notice the nullable column. The follow-up is almost always "now show the whole chain", which is testing whether you know recursive CTEs exist rather than expecting you to write one from memory.
employee
6 rows
| idinteger | nametext | manager_idinteger |
|---|---|---|
| 1 | Alice | |
| 2 | Bob | 1 |
| 3 | Carol | 1 |
| 4 | Dan | 3 |
| 5 | Erin | 3 |
Showing 5 of 6 rows.