skip to content

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
the top of the org dataset, from employees: each row's manager_id points at the row above it. click a node to fold it. the numbers are ids.
sqldb=org
SELECT id, name, manager_id, title FROM employees WHERE id <= 11 ORDER BY id;
output, from postgres 18.6
SELECT 11
idint4nametextmanager_idint4titletext
1Fatima Lopeznullceo
2Olivia Lopez1vp
3Mei Dubois1vp
4Chen Smith1vp
5Rahul Singh2director
6Amelia Hansen2director
7Olivia Singh2director
8Noah Silva3director
9Valentina Haddad3director
10Kenji Larsen3director
11Valentina Okafor4director
(11 rows)

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:

sqldb=org
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;
output, from postgres 18.6
SELECT 4
depthint4peopleint8
13
29
327
481
(4 rows)

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:

model =
team.sql
  1. 1WITH RECURSIVE team AS (
  2. 2 SELECT id, 1 AS depth FROM employees WHERE manager_id = 2
  3. 3 UNION ALL
  4. 4 SELECT e.id, team.depth + 1 FROM employees AS e JOIN team ON e.manager_id = team.id
  5. 5)
  6. 6SELECT count(*) AS reports, max(depth) AS levels FROM team;
the result for adjacency list
reportsint8levelsint4
1204
(1 row)

adjacency list: a recursive CTE walks down from Olivia Lopez (id 2), one level per round.

real output, postgres 18.6 (PGlite 0.5.12) · trees
the same question, "everyone under Olivia Lopez (id 2)", against four models built from the same org data. same answer each time. compare the shape of each query: a recursion, a prefix, a range, a lookup. nested sets don't know depth without more work, hence the null.
  • materialized path stores 1.2.5.17 on each row. a subtree is a prefix match (LIKE '1.2.%', which a b-tree with text_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:

add one person under Rahul Singh
adjacency list1 rows
materialized path1 rows
closure table4 rows
nested sets520 rows
move Rahul Singh's team under Mei Dubois
adjacency list1 rows
materialized path41 rows
closure table164 rows
rows written to add one employee, and to move a 41-person team, per model. the adjacency list always writes one row. nested sets renumber half the table for a single insert; the closure table rewrites every pair crossing the move.

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:

sqldb=org · ext=ltree
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);
output, from postgres 18.6
#1 · SELECT 300
#2 · CREATE INDEX
#3 · SELECT 1
teamint8
120
(1 row)
#4 · SELECT 6
pathltreenametext
1Fatima Lopez
1.4Chen Smith
1.4.11Valentina Okafor
1.4.11.32Mei Kowalski
1.4.11.32.96Amelia Yilmaz
1.4.11.32.96.287Lucas Kim
(6 rows)

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

modelsubtree readancestorsadd a nodemove a subtreeintegrity
adjacency listrecursive CTErecursive CTE1 row1 rowforeign key on parent
path / ltreeprefix or <@, indexedparse the path1 rowevery row in the subtreenone built in
nested setsrangerangerenumber half the tablerenumbernone built in
closure tableone lookupone lookupdepth + 1 rowssubtree × ancestorsforeign 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.

predict the output
sql
-- 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.