Database Relationships and Diagrams · Lesson 25 of 112

Database Trees and Self-references

What you will learn

  • What a self-reference is
  • How to store a hierarchy (a tree) in one table
  • How to list direct reports with a self-join
  • How a recursive query walks the whole tree
  • What the database refuses

1. A table that points to itself

Some data is a hierarchy: employees and managers, folders in folders, categories in sub-categories, replies to comments. Each item has at most one parent of the same kind.

You do not need a second table. Put a foreign key in the table that points to its own primary key:

employees
+----+--------+------------+
| id | name   | manager_id |
+----+--------+------------+
|  1 | Aisha  |    NULL    |  <- the top has no manager
|  2 | Bilal  |     1      |
|  3 | Chitra |     1      |
|  4 | Dev    |     2      |
+----+--------+------------+

This is a one-to-many relationship from a table to itself: one manager has many employees, each employee has at most one manager. The top of the tree (the root) has NULL as its parent.

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Run the examples from top to bottom, and press Reset data to start again.

The Shop has a real tree: employees.manager_id points to employees.employee_id. The top person has no manager:

SELECT employee_id, name, role, manager_id FROM employees ORDER BY employee_id LIMIT 6;
employee_id  name           role        manager_id
-----------  -------------  ----------  ----------
          1  Chen Nguyen    Manager           NULL
          2  Isla Banerjee  Sales lead           1
          3  Gita Uddin     Sales lead           1
          4  Mina Kamau     Sales                2
          5  Yusuf Kumar    Sales                2
          6  Kofi Bianchi   Sales                2
(6 rows)

The Bank has no tree of its own, so make one: a table of staff with a manager_id that points to the same table. The top person has no manager:

CREATE TABLE bank_staff (
    id         INTEGER PRIMARY KEY,
    name       TEXT NOT NULL,
    manager_id INTEGER REFERENCES bank_staff (id)
);
INSERT INTO bank_staff VALUES (1,'Aisha',NULL),(2,'Bilal',1),(3,'Chitra',1),(4,'Dev',2),(5,'Esha',2),(6,'Farid',4);
SELECT * FROM bank_staff ORDER BY id;
id  name    manager_id
--  ------  ----------
 1  Aisha         NULL
 2  Bilal            1
 3  Chitra           1
 4  Dev              2
 5  Esha             2
 6  Farid            4
(6 rows)

The School has no tree of its own, so make one: a table of units (the school, its stages, its years, its classes) with a parent_id that points to the same table. The top unit has no parent:

CREATE TABLE school_units (
    id        INTEGER PRIMARY KEY,
    name      TEXT NOT NULL,
    parent_id INTEGER REFERENCES school_units (id)
);
INSERT INTO school_units VALUES (1,'Whole school',NULL),(2,'Primary',1),(3,'Secondary',1),(4,'Year 1',2),(5,'Year 2',2),(6,'Class 1A',4);
SELECT * FROM school_units ORDER BY id;
id  name          parent_id
--  ------------  ---------
 1  Whole school       NULL
 2  Primary               1
 3  Secondary             1
 4  Year 1                2
 5  Year 2                2
 6  Class 1A              4
(6 rows)

2. One level: a self-join

To show each row with its parent's name, join the table to itself using two different aliases (e for the row, m for its parent):

SELECT e.employee_id, e.name, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.employee_id = e.manager_id
ORDER BY e.employee_id
LIMIT 6;
employee_id  name           manager
-----------  -------------  -------------
          1  Chen Nguyen    NULL
          2  Isla Banerjee  Chen Nguyen
          3  Gita Uddin     Chen Nguyen
          4  Mina Kamau     Isla Banerjee
          5  Yusuf Kumar    Isla Banerjee
          6  Kofi Bianchi   Isla Banerjee
(6 rows)
SELECT employee_id, name FROM employees WHERE manager_id = 2 ORDER BY employee_id;
employee_id  name
-----------  ------------
          4  Mina Kamau
          5  Yusuf Kumar
          6  Kofi Bianchi
(3 rows)
SELECT e.id, e.name, m.name AS manager
FROM bank_staff e
LEFT JOIN bank_staff m ON m.id = e.manager_id
ORDER BY e.id;
id  name    manager
--  ------  -------
 1  Aisha   NULL
 2  Bilal   Aisha
 3  Chitra  Aisha
 4  Dev     Bilal
 5  Esha    Bilal
 6  Farid   Dev
(6 rows)
SELECT name FROM bank_staff WHERE manager_id = 2 ORDER BY id;
name
----
Dev
Esha
(2 rows)
SELECT e.id, e.name, m.name AS parent
FROM school_units e
LEFT JOIN school_units m ON m.id = e.parent_id
ORDER BY e.id;
id  name          parent
--  ------------  ------------
 1  Whole school  NULL
 2  Primary       Whole school
 3  Secondary     Whole school
 4  Year 1        Primary
 5  Year 2        Primary
 6  Class 1A      Year 1
(6 rows)
SELECT name FROM school_units WHERE parent_id = 2 ORDER BY id;
name
------
Year 1
Year 2
(2 rows)

The LEFT JOIN keeps the top row, which has no parent. The second query lists the direct children of row 2. But the children of those children are below row 2 too, only indirectly. A fixed number of joins cannot follow a tree of unknown depth.

3. The whole tree: a recursive query

A recursive query (WITH RECURSIVE) starts with some rows and repeatedly adds the rows that link to them, until nothing new is found:

WITH RECURSIVE tree(id, name, depth) AS (
    SELECT employee_id, name, 0 FROM employees WHERE employee_id = 1
    UNION ALL
    SELECT e.employee_id, e.name, t.depth + 1
    FROM employees e JOIN tree t ON e.manager_id = t.id
)
SELECT depth, name FROM tree ORDER BY depth, id LIMIT 8;
depth  name
-----  -------------
    0  Chen Nguyen
    1  Isla Banerjee
    1  Gita Uddin
    1  Mina Park
    1  Ugo Rahman
    2  Mina Kamau
    2  Yusuf Kumar
    2  Kofi Bianchi
(8 rows)
WITH RECURSIVE tree(id, name, depth) AS (
    SELECT id, name, 0 FROM bank_staff WHERE id = 1
    UNION ALL
    SELECT e.id, e.name, t.depth + 1
    FROM bank_staff e JOIN tree t ON e.manager_id = t.id
)
SELECT depth, name FROM tree ORDER BY depth, id;
depth  name
-----  ------
    0  Aisha
    1  Bilal
    1  Chitra
    2  Dev
    2  Esha
    3  Farid
(6 rows)
WITH RECURSIVE tree(id, name, depth) AS (
    SELECT id, name, 0 FROM school_units WHERE id = 1
    UNION ALL
    SELECT e.id, e.name, t.depth + 1
    FROM school_units e JOIN tree t ON e.parent_id = t.id
)
SELECT depth, name FROM tree ORDER BY depth, id;
depth  name
-----  ------------
    0  Whole school
    1  Primary
    1  Secondary
    2  Year 1
    2  Year 2
    3  Class 1A
(6 rows)

The first SELECT is the start (the root, level 0). The second finds every row whose parent is already in tree, one level deeper each round, until no new rows appear. The result lists rows by level, not by branch. Recursive queries are covered in the SQL course; here you only need the idea.

Everyone under one row, at any depth, compared with its direct children:

Under employee 1 (the manager), the direct reports and everybody below:

SELECT COUNT(*) AS direct_reports FROM employees WHERE manager_id = 1;
WITH RECURSIVE t(id) AS (
    SELECT employee_id FROM employees WHERE manager_id = 1
    UNION ALL
    SELECT e.employee_id FROM employees e JOIN t ON e.manager_id = t.id
)
SELECT COUNT(*) AS everyone_below FROM t;
direct_reports
--------------
             4
(1 row)

everyone_below
--------------
            13
(1 row)

Under row 2, the direct children and everybody below:

SELECT COUNT(*) AS direct_reports FROM bank_staff WHERE manager_id = 2;
WITH RECURSIVE t(id) AS (
    SELECT id FROM bank_staff WHERE manager_id = 2
    UNION ALL
    SELECT e.id FROM bank_staff e JOIN t ON e.manager_id = t.id
)
SELECT COUNT(*) AS everyone_below FROM t;
direct_reports
--------------
             2
(1 row)

everyone_below
--------------
             3
(1 row)

Under row 2, the direct children and everybody below:

SELECT COUNT(*) AS direct_children FROM school_units WHERE parent_id = 2;
WITH RECURSIVE t(id) AS (
    SELECT id FROM school_units WHERE parent_id = 2
    UNION ALL
    SELECT e.id FROM school_units e JOIN t ON e.parent_id = t.id
)
SELECT COUNT(*) AS everyone_below FROM t;
direct_children
---------------
              2
(1 row)

everyone_below
--------------
             3
(1 row)

4. Guarding the tree

The foreign key still protects the structure. Pointing a row at a parent that does not exist is refused:

UPDATE employees SET manager_id = 999 WHERE employee_id = 6;
IntegrityError: FOREIGN KEY constraint failed
UPDATE bank_staff SET manager_id = 99 WHERE id = 6;
IntegrityError: FOREIGN KEY constraint failed
UPDATE school_units SET parent_id = 99 WHERE id = 6;
IntegrityError: FOREIGN KEY constraint failed

A plain foreign key does not stop a loop (A manages B, B manages A), which would make a recursive query run forever. Preventing cycles needs extra checks in your application or database-specific features.

Worked example: folders

A folders(id, name, parent_id REFERENCES folders(id)) table stores a file system.

Folder parent_id
Documents NULL
Photos 1
Holiday 2

"Holiday" is inside "Photos", which is inside "Documents". The path of any folder is found by following parent_id upward; its contents by following it downward. Names are made up.

Common mistakes

  • Using several columns (level1, level2, level3) for a tree of unknown depth.
  • Forgetting the root's NULL and giving it a fake parent.
  • Using an inner join and losing the root in a manager list.
  • Allowing cycles without any check.

Key takeaways

  • A foreign key can point to the same table's primary key.
  • The root of the tree has NULL as its parent.
  • A self-join with two aliases shows parent and child side by side.
  • WITH RECURSIVE walks the tree to any depth.
  • A foreign key checks the parent exists but does not prevent loops.

Practice

1. Which column makes employees a tree?

Show answer

manager_id, which references employees(id).

2. What value does the top person have in manager_id?

Show answer

NULL.

3. Why does the lesson use two aliases, e and m?

Show answer

The same table appears twice in the query, once as the employee and once as the manager, so each needs its own name.

4. Who are Bilal's direct reports, and who are all his reports?

Show answer

Direct: Dev and Esha. All (including indirect): Dev, Esha and Farid.

5. What is one thing a plain foreign key cannot prevent in a tree?

Show answer

A cycle, such as two people managing each other.

6. Design a table for comments where a comment can reply to another comment.

Show answer

comments(id, body, parent_id REFERENCES comments(id)), with parent_id empty for a top-level comment.