Sub topic 5
Keeping the top of the hierarchy with a LEFT self join
This chapter assumes you can write an INNER JOIN and a LEFT JOIN with an ON condition, and that you know primary keys, foreign keys, NULL behavior, and GROUP BY with aggregates. It also assumes you have seen the basic employee-and-manager self join with aliases. Here you will fix the main weakness of that query: it silently drops the person at the top of the hierarchy.
The problem: the top row disappears
The examples use the employees table. Each row stores its manager's id in manager_id, and the top person has NULL there.
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);The reporting structure is Ava at the top, Ben and Chen under Ava, and Dana under Ben.
The INNER JOIN version of the self join looks like this:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id;It returns three rows (Ben, Chen, Dana). Ava is missing. Her manager_id is NULL, and a comparison with NULL is never true, so e.manager_id = m.id finds no partner for her. An INNER JOIN keeps only rows that found a partner, so Ava is discarded.
If you are building an org chart, a headcount report, or a data-quality check, losing the root row is a bug that produces no error. The query runs and looks plausible.
The fix: LEFT JOIN
A LEFT JOIN keeps every row from the left table, whether or not the ON condition finds a match. For the unmatched rows, every column from the right table is filled with NULL.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;| employee | manager |
|---|---|
| Ava | NULL |
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
Nothing about the self join changed except the join type. The alias e still plays the employee role and m still plays the manager role. They are two names for the same physical table. The role that you want to preserve must be on the left side of the LEFT JOIN, which here is e.
Reading the NULL
After the change, a NULL in the manager column has a specific meaning: the employee had no matching manager row. In this table that means the employee is the root of the hierarchy. You can make that explicit in a report with COALESCE:
SELECT e.name AS employee,
COALESCE(m.name, '(top of hierarchy)') AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;Be careful with what NULL can mean. There are two different causes of a NULL manager:
- The employee's
manager_idis NULL. They have no manager by design. - The employee's
manager_idholds a value, but no row has thatid. This is a dangling reference.
The foreign key REFERENCES employees(id) prevents the second case in this table. If your data comes from a table without that constraint, such as an imported file or a legacy schema, you can separate the cases by also selecting e.manager_id. A row with a non-NULL manager_id and a NULL manager name is an orphan.
SELECT e.id, e.name, e.manager_id
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE e.manager_id IS NOT NULL
AND m.id IS NULL;This is an anti-join: join, then keep rows where the right side is missing. On the sample data it returns zero rows, which is the result you want from a healthy table.
Pitfall: filtering the manager in WHERE
The most common LEFT JOIN mistake is a WHERE condition on the right-hand alias. Suppose you want every employee whose manager is not Ben:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE m.name <> 'Ben';For Ava, m.name is NULL, and NULL <> 'Ben' evaluates to unknown, not true. WHERE keeps only rows where the condition is true, so Ava is removed again. The LEFT JOIN has been undone by the filter, and the result is the same as an INNER JOIN would give (Ben and Chen).
There are two ways to fix it. The first is to handle NULL explicitly:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE m.name IS NULL OR m.name <> 'Ben'
ORDER BY e.id;This returns Ava, Ben, and Chen. Dana is excluded because her manager is Ben. Some databases, such as PostgreSQL, also offer IS DISTINCT FROM, which treats NULL as an ordinary value. It is not available everywhere, so the IS NULL OR form is the portable choice.
The second fix is to decide whether the condition belongs in ON or WHERE. They do different jobs in a LEFT JOIN:
| Placement | What it controls | Effect on left rows |
|---|---|---|
| `ON` | Which right rows count as a match | Left rows are always kept. Unmatched ones get NULLs. |
| `WHERE` | Which result rows survive | Left rows can be removed, including ones with NULLs. |
To see the difference, move a condition on m into ON:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.id
AND m.name = 'Ava'
ORDER BY e.id;| employee | manager |
|---|---|
| Ava | NULL |
| Ben | Ava |
| Chen | Ava |
| Dana | NULL |
All four employees are present. Dana's manager is Ben, which fails the m.name = 'Ava' test, so she has no match and her manager shows as NULL. Use ON when you mean "show the manager only if it meets this condition" and WHERE when you mean "drop employees who do not meet this condition".
Flipping the direction: managers and their reports
The same table can be read from the other side. If you put the manager role on the left, the LEFT JOIN preserves every person as a manager, including people who manage nobody:
SELECT m.name AS manager, e.name AS report
FROM employees m
LEFT JOIN employees e ON e.manager_id = m.id
ORDER BY m.id, e.id;| manager | report |
|---|---|
| Ava | Ben |
| Ava | Chen |
| Ben | Dana |
| Chen | NULL |
| Dana | NULL |
Chen and Dana are leaves of the hierarchy, so their report is NULL. Keeping only those rows is the anti-join pattern again:
SELECT m.name AS employee_without_reports
FROM employees m
LEFT JOIN employees e ON e.manager_id = m.id
WHERE e.id IS NULL
ORDER BY m.id;Test for NULL on a column that can never be NULL in a real match, such as the primary key e.id. If you test a nullable column like e.manager_id, you could not tell a missing match from a genuine NULL value.
Counting direct reports
Combining this direction with GROUP BY shows the most frequent trap with aggregates. To report the number of direct reports per person, including zero:
SELECT m.name AS manager,
COUNT(e.id) AS direct_reports
FROM employees m
LEFT JOIN employees e ON e.manager_id = m.id
GROUP BY m.id, m.name
ORDER BY m.id;| manager | direct_reports |
|---|---|
| Ava | 2 |
| Ben | 1 |
| Chen | 0 |
| Dana | 0 |
COUNT(e.id) counts only non-NULL values, so the NULL-extended rows for Chen and Dana count as zero. COUNT(*) would report 1 for them, because it counts rows, and the NULL-extended row is still a row. Count a column from the optional side of the join.
Chaining LEFT self joins
You can add the same table a third time to reach a manager's manager. Every join in the chain must be a LEFT JOIN, or an INNER JOIN later in the chain will remove the rows that the earlier LEFT JOIN preserved.
SELECT e.name AS employee,
m.name AS manager,
gm.name AS grand_manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
LEFT JOIN employees gm ON m.manager_id = gm.id
ORDER BY e.id;| employee | manager | grand_manager |
|---|---|---|
| Ava | NULL | NULL |
| Ben | Ava | NULL |
| Chen | Ava | NULL |
| Dana | Ben | Ava |
Each extra level needs one more alias and one more join, and the query only works for a depth you know ahead of time. When the depth is unknown, or you need the full chain for every employee, a recursive query is the better tool. That is the subject of a later chapter.
Quick checklist
- Decide which role must never lose rows, and put its alias on the left of the LEFT JOIN.
- Use distinct, meaningful aliases and qualify every column (
e.name,m.name). - Put conditions on the optional side in
ONunless you deliberately want to drop rows. - Test for a missing match with the primary key of the optional side (
m.id IS NULL). - In aggregates, count a column from the optional side, not
*. - In a chain of joins, keep every link a LEFT JOIN.
Exercise
Using the employees table from this chapter, write a query that lists every employee with the name of their manager, showing the text 'none' for the employee who has no manager, and then explain what happens to the result if you add WHERE m.name <> 'Ben' to it.
Show answer
SELECT e.name AS employee, COALESCE(m.name, 'none') AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id ORDER BY e.id; This returns Ava with 'none', Ben with Ava, Chen with Ava, and Dana with Ben. Adding WHERE m.name <> 'Ben' removes Dana, as intended, but it also removes Ava. Ava's m.name is NULL, NULL <> 'Ben' is unknown rather than true, and WHERE keeps only true rows. The condition must be written as WHERE m.name IS NULL OR m.name <> 'Ben' to keep her.
Exercise
Write a query that returns each person's name and the number of direct reports they have, including people with zero. Why does COUNT(*) give the wrong answer here?
Show answer
SELECT m.name AS manager, COUNT(e.id) AS directreports FROM employees m LEFT JOIN employees e ON e.managerid = m.id GROUP BY m.id, m.name ORDER BY m.id; The result is Ava 2, Ben 1, Chen 0, Dana 0. COUNT(*) counts rows, and a person with no reports still produces one NULL-extended row in the LEFT JOIN, so Chen and Dana would be reported as 1. COUNT(e.id) ignores NULLs and gives 0.