Sub topic 14
Self-Referencing Keys for Hierarchies
Assume you know CREATE TABLE, foreign keys, NULL, and basic SELECT, INSERT, and DELETE. A self-referencing foreign key is a foreign key that points back to the same table. It models a hierarchy, such as employees and managers, folders and parent folders, or categories and parent categories.
Modeling a hierarchy
An employee row can store the key of another employee as its manager. A top-level employee has no manager, so manager_id is NULL.
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
);
INSERT INTO employees (name, manager_id)
VALUES
('Maya', NULL),
('Luis', 1),
('Nora', 1),
('Owen', 2);The foreign key requires every non-NULL manager_id to match an existing employee_id. The NULL value represents an optional relationship. It means “this employee has no manager recorded,” not “use a special manager row.”
ON DELETE SET NULL prevents deleting a manager from deleting the manager's subordinates. Instead, their manager_id values become NULL. Other choices include ON DELETE CASCADE, which deletes subordinates, or the default NO ACTION, which rejects the delete while references remain.
Querying parent and child rows
A self-join uses two aliases for the same table. One alias represents the employee and the other represents the manager.
SELECT
employee.name AS employee,
manager.name AS manager
FROM employees AS employee
LEFT JOIN employees AS manager
ON employee.manager_id = manager.employee_id
ORDER BY employee.employee_id;The LEFT JOIN keeps top-level employees in the result. An inner JOIN would omit rows whose manager_id is NULL.
For deeper levels, PostgreSQL supports a recursive common table expression. It starts with top-level employees, then repeatedly finds their direct reports.
WITH RECURSIVE org AS (
SELECT employee_id, name, manager_id, 0 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT child.employee_id, child.name, child.manager_id, org.level + 1
FROM employees AS child
JOIN org ON child.manager_id = org.employee_id
)
SELECT level, name
FROM org
ORDER BY level, employee_id;Constraints and design risks
The foreign key prevents a reference to a missing employee, but it does not automatically prevent every logical problem. For example, an employee could be assigned as their own manager, or rows could form a cycle.
Defining the column as NOT NULL would require every employee to have a manager, which would make top-level rows impossible. Use NULL when the relationship is genuinely optional.
Exercise
What happens to an employee's manager_id when their manager is deleted from the example table?
Show answer
ON DELETE SET NULL changes manager_id to NULL, leaving the employee row in place without a manager.