Sub topic 14
Self-referencing keys for hierarchies
This chapter assumes you can write CREATE TABLE statements with primary keys and foreign keys, and that you know joins and NULL. Some hierarchies, such as an org chart, a category tree, or a comment thread, hold rows of one kind that point at other rows of the same kind. You model them with a self-referencing foreign key, which is a foreign key whose parent table is its own table.
The adjacency list pattern
Each row stores a pointer to its parent. This layout is called an adjacency list.
CREATE TABLE employees (
employee_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id) ON DELETE SET NULL
);The manager_id column is nullable on purpose. The top of the hierarchy has no manager, and NULL represents that. A foreign key is only checked when the value is not NULL, so the top-level row is valid without a parent.
Load a small tree. On a freshly created table the identity column hands out 1, 2, 3 and so on, so the manager ids below match the rows inserted before them.
INSERT INTO employees (name, manager_id) VALUES ('Ada', NULL);
INSERT INTO employees (name, manager_id) VALUES ('Ben', 1);
INSERT INTO employees (name, manager_id) VALUES ('Cleo', 1);
INSERT INTO employees (name, manager_id) VALUES ('Dev', 2);
INSERT INTO employees (name, manager_id) VALUES ('Eli', 2);The arrows show who manages whom. In the table, each child row stores the parent's primary key, so the arrow points in the opposite direction from the foreign key reference.
Insert order and what is rejected
The parent row must exist before the child row. Inserting Dev with manager_id 2 only works because Ben was already inserted. The database rejects a pointer to a missing row, exactly as with any other foreign key:
-- Fails: no employee with employee_id 99
INSERT INTO employees (name, manager_id) VALUES ('Fay', 99);A single multi-row INSERT can contain both a parent and its children. PostgreSQL checks the foreign key after the statement finishes, so the order of rows inside one statement does not matter. Separate statements need parents first, unless the constraint is deferrable (a later chapter covers that).
Querying one level: the self-join
To list each employee next to their manager, join the table to itself. Give the two uses different aliases so the columns are unambiguous.
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;Use LEFT JOIN. An INNER JOIN drops Ada, because her manager_id is NULL and matches nothing. The left join keeps her and shows NULL in the manager column.
Querying all levels: recursive CTEs
A self-join reaches one level per join. To walk a tree of unknown depth, use a recursive common table expression (CTE). It has a starting query, the roots, and a recursive step that repeatedly joins children to the rows found so far.
WITH RECURSIVE org AS (
SELECT employee_id, name, manager_id, 1 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, e.manager_id, o.depth + 1
FROM employees AS e
JOIN org AS o ON e.manager_id = o.employee_id
)
SELECT name, depth
FROM org
ORDER BY depth, name;For the sample data this returns Ada at depth 1, Ben and Cleo at depth 2, and Dev and Eli at depth 3. Recursive CTEs are supported by PostgreSQL, MySQL 8, SQL Server, and Oracle. SQL Server and Oracle differ slightly in syntax: SQL Server omits the RECURSIVE keyword, and Oracle also has its own CONNECT BY syntax.
Choosing the ON DELETE action
The action you pick decides what happens to a whole subtree when its parent is deleted.
| Action | Deleting Ben | Typical use |
|---|---|---|
| `NO ACTION` or `RESTRICT` | Rejected while Dev or Eli still reference Ben | Force the caller to reassign children first |
| `SET NULL` | Dev and Eli become top-level rows | Optional parents, such as managers who leave |
| `CASCADE` | Dev and Eli are deleted as well, and so are their descendants | Data that has no meaning without its parent, such as replies to a deleted comment |
CASCADE on a self-reference is powerful. One DELETE can remove an entire branch, so use it only when losing the branch is the intended behavior. SET NULL can silently turn orphaned subtrees into extra roots, which may surprise queries that assume a single root.
What the foreign key does not protect against
The foreign key guarantees that every parent exists. It does not guarantee that the structure is a tree. Two gaps are common.
A row can point at itself:
UPDATE employees SET manager_id = 1 WHERE employee_id = 1;This succeeds, because employee 1 exists. Block it with a check constraint. A NULL manager_id makes the check evaluate to unknown, which counts as passing, so top-level rows are unaffected.
ALTER TABLE employees
ADD CONSTRAINT ck_employees_not_own_manager
CHECK (manager_id <> employee_id);Longer cycles are also accepted. Setting Ada's manager to Dev makes Ada manage Ben, Ben manage Dev, and Dev manage Ada:
UPDATE employees SET manager_id = 4 WHERE employee_id = 1;Every referenced row exists, so the foreign key is satisfied. Now no row has a NULL manager_id, so the recursive query above finds no roots and returns nothing. A query that walks upward from Dev would loop forever. Defenses include checking for cycles in application code or a trigger before changing a parent, limiting recursion with a depth < 20 condition, and using the CYCLE clause available in PostgreSQL 14 and later.
Index the pointer column
Finding all children of a manager is a lookup on manager_id, and the recursive step runs that lookup once per level. Deleting or updating a parent row also searches for children. PostgreSQL does not create an index for a foreign key automatically, so add one:
CREATE INDEX idx_employees_manager_id ON employees (manager_id);Alternatives to the adjacency list
The adjacency list is simple to write and cheap to update, because moving a branch changes one row. Its weakness is that reading a whole subtree needs a recursive query. Other models, such as a stored path or a closure table with one row per ancestor and descendant pair, make subtree reads faster at the cost of more writes and extra upkeep. Start with the adjacency list unless you have measured a problem.
Exercise
Using the employees table above with ON DELETE SET NULL, what happens to Dev and Eli if you run DELETE FROM employees WHERE employee_id = 2? What would change if the action were CASCADE?
Show answer
With SET NULL, Ben is deleted and the manager_id of Dev and Eli becomes NULL, so both appear as top-level rows. With CASCADE, Dev and Eli are deleted along with Ben, and so would be any employees who reported to them.