storing trees
adjacency list, ltree paths, closure tables. pick the shape by the queries you'll run.
- address
- everything.design.hierarchies
- part
- part 7, schema design
- chapter
- chapter 8 of 13
- reading time
- 8 min
a tree in a table is usually an adjacency list: each row points at its parent (manager_id), and a recursive CTE walks it. it's the simplest to write to and fine to read for most trees.
when "everything under this node" has to be one indexed lookup, store more: a materialized path (1.2.5, or the ltree type), a closure table of every ancestor-descendant pair, or nested sets (lft/rgt numbers). each makes reads cheaper and some writes much more expensive. pick by the queries you'll run, and by how often the tree changes.
the picture
you know the org chart question: "everyone who reports to Olivia, directly or not"? with one manager_id per row, there's no column that says "is somewhere under Olivia". you have to follow the pointers, one level at a time.
think of a family tree. you can store it as "each person names their mother" (adjacency), as "each person writes out their whole line of descent on their card" (path), or as a big ledger of every ancestor-descendant pair (closure table). the first is quickest to update when a baby arrives; the last answers "all of grandma's descendants" by reading one page of the ledger.
the org dataset is a tree like this, 300 people, 6 levels:
- ceo, 1
- ├── vp, 2 (the subtree below)
- │ ├── Rahul Singhdirector, 5
- │ ├── Amelia Hansendirector, 6
- │ └── Olivia Singhdirector, 7
- ├── vp, 3
- │ ├── Noah Silvadirector, 8
- │ ├── Valentina Haddaddirector, 9
- │ └── Kenji Larsendirector, 10
- └── vp, 4
- └── Valentina Okafordirector, 11
employees: each row's manager_id points at the row above it. click a node to fold it. the numbers are ids.SELECT id, name, manager_id, title FROM employees WHERE id <= 11 ORDER BY id;| idint4 | nametext | manager_idint4 | titletext |
|---|---|---|---|
| 1 | Fatima Lopez | null | ceo |
| 2 | Olivia Lopez | 1 | vp |
| 3 | Mei Dubois | 1 | vp |
| 4 | Chen Smith | 1 | vp |
| 5 | Rahul Singh | 2 | director |
| 6 | Amelia Hansen | 2 | director |
| 7 | Olivia Singh | 2 | director |
| 8 | Noah Silva | 3 | director |
| 9 | Valentina Haddad | 3 | director |
| 10 | Kenji Larsen | 3 | director |
| 11 | Valentina Okafor | 4 | director |
adjacency list and a recursive CTE
the table already is one. walking down is a recursive CTE: start from Olivia's direct reports, and keep joining employees whose manager is in the last round:
WITH RECURSIVE team AS (
SELECT id, name, 1 AS depth FROM employees WHERE manager_id = 2
UNION ALL
SELECT e.id, e.name, team.depth + 1
FROM employees AS e JOIN team ON e.manager_id = team.id
)
SELECT depth, count(*) AS people FROM team GROUP BY depth ORDER BY depth;| depthint4 | peopleint8 |
|---|---|
| 1 | 3 |
| 2 | 9 |
| 3 | 27 |
| 4 | 81 |
walking up, the chain of command from anyone to the CEO, is the same shape in the other direction. with an index on manager_id, each round is an index lookup per row of the previous round, so the cost grows with the size of the answer, not of the table. for an org chart, a category tree or threaded comments, that's usually all you need. writes are one row: add a person, move a team, all a single UPDATE of manager_id.
what it can't do: answer "is 287 under 2?" without walking, or give you the subtree from an index in one probe. a foreign key on manager_id also can't stop a cycle (A manages B manages A); the CTE's CYCLE clause detects them when you read.
three ways to store more
each of these keeps the adjacency list's facts and precomputes the ancestry. all four answer "Olivia's team" correctly:
- 1WITH RECURSIVE team AS (
- 2 SELECT id, 1 AS depth FROM employees WHERE manager_id = 2
- 3 UNION ALL
- 4 SELECT e.id, team.depth + 1 FROM employees AS e JOIN team ON e.manager_id = team.id
- 5)
- 6SELECT count(*) AS reports, max(depth) AS levels FROM team;
| reportsint8 | levelsint4 |
|---|---|
| 120 | 4 |
adjacency list: a recursive CTE walks down from Olivia Lopez (id 2), one level per round.
- materialized path stores
1.2.5.17on each row. a subtree is a prefix match (LIKE '1.2.%', which a b-tree withtext_pattern_ops, or the C collation, can serve), and the ancestors are the path itself. moving a subtree rewrites every path in it. - nested sets number nodes in a depth-first walk: each gets lft and rgt, and a node's subtree is exactly the nodes numbered between them. reads are a range scan; inserting anywhere renumbers everything to the right.
- closure table stores every (ancestor, descendant, depth) pair. 300 people need 1,621 rows here. subtree and ancestor queries are one lookup each, in either direction, and depth comes free.
what the writes cost
now add one person under Rahul Singh, then move Rahul's whole team under Mei Dubois. the row counts are what each model's statements reported:
nested sets were a classic in databases without recursive queries. in postgres, with recursive CTEs since 8.4, they're rarely worth that insert cost; the moving-team case isn't even shown, since it renumbers much of the table. the closure table's moves cost pairs (subtree size times ancestors) but its inserts stay small, which suits trees that grow a lot and move rarely.
ltree
postgres ships a materialized path type as a contrib extension: ltree stores labels like 1.2.5, with operators for ancestor and descendant (@>, <@), pattern matching, and GiST index support. ext=ltree creates it before the block runs:
CREATE TABLE org_paths AS
WITH RECURSIVE t AS (
SELECT id, name, text2ltree(id::text) AS path FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, t.path || e.id::text FROM employees AS e JOIN t ON e.manager_id = t.id
) SELECT * FROM t;
CREATE INDEX ON org_paths USING gist (path);
SELECT count(*) AS team FROM org_paths WHERE path <@ '1.2' AND path <> '1.2';
SELECT path, name FROM org_paths WHERE path @> (SELECT path FROM org_paths WHERE id = 287) ORDER BY nlevel(path);| teamint8 |
|---|
| 120 |
| pathltree | nametext |
|---|---|
| 1 | Fatima Lopez |
| 1.4 | Chen Smith |
| 1.4.11 | Valentina Okafor |
| 1.4.11.32 | Mei Kowalski |
| 1.4.11.32.96 | Amelia Yilmaz |
| 1.4.11.32.96.287 | Lucas Kim |
the same 120, and the chain from employee 287 up to the CEO read straight off the path. ltree is the path model with real operators and an index that understands them; moving a subtree still rewrites every path under it.
picking one
| model | subtree read | ancestors | add a node | move a subtree | integrity |
|---|---|---|---|---|---|
| adjacency list | recursive CTE | recursive CTE | 1 row | 1 row | foreign key on parent |
| path / ltree | prefix or <@, indexed | parse the path | 1 row | every row in the subtree | none built in |
| nested sets | range | range | renumber half the table | renumber | none built in |
| closure table | one lookup | one lookup | depth + 1 rows | subtree × ancestors | foreign keys on both columns |
start with the adjacency list. add a path or a closure table, kept in sync by a trigger, when a measured subtree query is too slow, which for most trees is never.
-- adjacency list: move Rahul Singh's team of 40 under Mei Dubois.
UPDATE employees SET manager_id = 3 WHERE id = 5;keylines
- an adjacency list (parent_id) plus a recursive CTE is the default, and writes are one row.
- materialized path and ltree make subtrees a prefix match; moves rewrite the subtree.
- a closure table stores every ancestor pair: one-lookup reads, more rows to write.
- nested sets make reads a range and inserts a renumbering.
- pick by the queries you run and how often the tree changes.