Sub topic 4
Employees and managers: reading a parent-child table
This chapter assumes you can write an INNER JOIN with an ON condition, you know what a primary key and a foreign key are, and you understand that NULL never equals anything. Earlier chapters covered aliases and the idea of a self join. Here you apply them to the most common real case: a table where each row points at another row in the same table.
What a parent-child table looks like
A parent-child table stores a hierarchy in one table. Each row holds a foreign key that points back to the primary key of another row in that same table. The employees table works this way:
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 manager_id column holds the id of the employee's manager. Ava has NULL because she has no manager. She is the root of the hierarchy. Ben and Chen report to Ava, and Dana reports to Ben.
The table holds only names and ids, so it does not show the tree. A plain SELECT returns manager_id as a number, and 2 tells a reader nothing unless they look up row 2. A self join does that lookup for every row at once.
Reading the join: one table, two roles
The query below returns each employee next to the name of their manager:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;The result has three rows:
| employee | manager |
|---|---|
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
The same physical table appears twice, and each alias gives it a different job:
| Alias | Role | Columns you read from it |
|---|---|---|
| `e` | The employee (the child row) | `e.name`, `e.manager_id` |
| `m` | The manager (the parent row) | `m.name`, `m.id` |
The ON condition connects the roles. It says "take the child's foreign key and find the parent whose primary key equals it." Read e.manager_id = m.id as "the manager of e is m".
How the database evaluates it
Conceptually, the database does this for each row e:
- Read
e.manager_id. - Look for rows
mwherem.idequals that value. - Emit one output row for each match, combining the columns of
eandm.
For Ben, manager_id is 1, so the match is Ava. For Dana, it is 2, so the match is Ben. For Ava, manager_id is NULL. The comparison NULL = m.id is never true for any m, so no match exists and an INNER JOIN drops her row.
The database does not literally make two copies of the table. An optimizer usually runs this as an index lookup on m.id, which is the primary key, so each employee costs about one lookup. The "two tables" view is a way to reason about the query, not a description of the work done.
Choosing the direction of the lookup
The same join can read in two directions. The ON condition is identical, but the alias you select from and the alias you group or order by decide the point of view.
Looking up from child to parent ("who is each person's manager?") returns one row per employee, because each employee has at most one manager. Looking down from parent to child ("who reports to each manager?") returns one row per reporting relationship, and a manager with several reports appears several times:
SELECT m.name AS manager, e.name AS report
FROM employees m
INNER JOIN employees e ON e.manager_id = m.id
ORDER BY m.id, e.id;| manager | report |
|---|---|
| Ava | Ben |
| Ava | Chen |
| Ben | Dana |
The ON clause has not changed. Only the order of the tables and the select list changed. Both queries produce the same set of three relationships and differ in which column you read first.
This direction matters when you aggregate. To count direct reports per manager, group by the parent alias:
SELECT m.name AS manager, COUNT(e.id) AS direct_reports
FROM employees m
INNER 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 and Dana are missing because they manage nobody, and an inner join only keeps parents that have at least one child. If you need a row with a count of 0 for every employee, use a LEFT JOIN here. The GROUP BY includes m.id and m.name because two employees could share a name, and grouping by id keeps them separate.
Going up more than one level
A single self join links a row to its parent. To reach the grandparent, join the table a third time and chain the aliases, so each new alias attaches to the previous one:
SELECT e.name AS employee,
m.name AS manager,
gm.name AS grand_manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
INNER JOIN employees gm ON m.manager_id = gm.id
ORDER BY e.id;The result has a single row:
| employee | manager | grand_manager |
|---|---|---|
| Dana | Ben | Ava |
Notice that the second ON uses m.manager_id, not e.manager_id. Each join must point from the alias just added to the one before it. If you wrote e.manager_id = gm.id by mistake, gm would be the same person as m, and the query would run without error and give a wrong answer.
Ben has a manager, but not a grandmanager, so the second inner join removes him. Chen is removed the same way. Each extra level removes more rows unless you switch the joins to LEFT JOIN.
This approach has a hard limit. The query has one join per level, so it can only reach the depth you wrote. If an organization has seven levels, you need six joins, and a new level means editing the query. Hierarchies of unknown depth need a recursive query, which the last chapter section covers.
Common errors
These mistakes produce wrong output without raising an error, so they are worth checking for:
- Reversed condition. Writing
e.id = m.manager_idswaps the roles. The query still runs, buteis now the manager andmis the employee, so the labels in your select list are wrong. Check the output against a few rows you know. - Unqualified columns. Writing
SELECT namefails with an "ambiguous column" error, because both aliases have anamecolumn. Qualify every column with its alias. - Missing
ORDER BY. SQL does not guarantee row order without it. Output that looks sorted on a small table can change on a larger one or after an index change. - Treating
NULLas a match. TryingON e.manager_id = m.id OR e.manager_id IS NULLdoes not help. TheIS NULLbranch would match everymand pair the root with every row. Use aLEFT JOINto keep root rows. - Cycles in the data. Nothing in the schema stops
manager_idvalues from forming a loop, such as Ava reporting to Dana. A fixed number of self joins ends anyway, so it survives a loop. A recursive query does not end unless you guard against loops. - Self-reference. A row with
manager_idequal to its ownidmakes an employee their own manager. ACHECK (manager_id <> id)constraint prevents this.
Checking your result
A quick way to check a hierarchy query is to compare counts. With an inner self join, the number of output rows must equal the number of employees whose manager_id is not NULL:
SELECT COUNT(*) AS rows_with_manager
FROM employees
WHERE manager_id IS NOT NULL;This returns 3, which matches the three rows of the first query. If the join returned more, the join key is probably matching several rows. If it returned fewer, some manager_id values point at ids that do not exist, which a foreign key normally prevents, or the condition is wrong. A mismatch tells you to look at the ON clause before looking at anything else.
Exercise
Write a query that returns each employee's name together with the name of their manager's manager, keeping only employees who have one. Using the sample data, which employee appears in the result, and why do Ben and Chen not appear?
Show answer
Join employees three times, chaining each alias to the previous one: FROM employees e INNER JOIN employees m ON e.managerid = m.id INNER JOIN employees gm ON m.managerid = gm.id, and select e.name and gm.name. Only Dana appears (with Ava as the manager's manager). Ben and Chen report to Ava, whose manager_id is NULL, so the second join finds no gm row for them and the inner join removes them. Ava is removed at the first join because she has no manager at all.