Database Design Patterns · Lesson 76 of 112

Database Hierarchies: Paths and Nested Sets

What you will learn

  • Three ways to store a tree in tables
  • How to read a whole branch and a breadcrumb with each
  • What it costs to move a branch
  • How to choose

Lesson 3.9 introduced a table that points at itself (parent_id). That is the adjacency list, the simplest way to store a hierarchy. This lesson compares it with two other designs, using one example menu:

Shop
├─ Clothes
│   ├─ Men
│   │   └─ Shirts
│   └─ Women
└─ Food
    └─ Tea

1. Adjacency list and recursive queries

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

Each row stores its parent. SQLite (like many systems) can walk the tree with a recursive query (WITH RECURSIVE).

The Shop already stores its categories this way (categories.parent_id). Everything below the category "Office" (id 4):

WITH RECURSIVE sub(id, name, depth) AS (
  SELECT category_id, name, 0 FROM categories WHERE category_id = 4
  UNION ALL SELECT c.category_id, c.name, sub.depth + 1 FROM categories c JOIN sub ON c.parent_id = sub.id)
SELECT depth, name FROM sub ORDER BY depth, name;
depth  name
-----  ----------
    0  Office
    1  Furniture
    1  Stationery
(3 rows)

Now a deeper tree of our own, used in the rest of the lesson (the path column is for section 2):

CREATE TABLE cat (id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER REFERENCES cat (id), path TEXT);
INSERT INTO cat VALUES
 (1, 'Shop', NULL, '/1/'), (2, 'Clothes', 1, '/1/2/'), (3, 'Men', 2, '/1/2/3/'), (4, 'Women', 2, '/1/2/4/'),
 (5, 'Shirts', 3, '/1/2/3/5/'), (6, 'Food', 1, '/1/6/'), (7, 'Tea', 6, '/1/6/7/');
WITH RECURSIVE sub(id, name, depth) AS (
  SELECT id, name, 0 FROM cat WHERE id = 2
  UNION ALL SELECT c.id, c.name, sub.depth + 1 FROM cat c JOIN sub ON c.parent_id = sub.id)
SELECT depth, name FROM sub ORDER BY depth, name;
depth  name
-----  -------
    0  Clothes
    1  Men
    1  Women
    2  Shirts
(4 rows)
CREATE TABLE cat (id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER REFERENCES cat (id), path TEXT);
INSERT INTO cat VALUES
 (1, 'Shop', NULL, '/1/'), (2, 'Clothes', 1, '/1/2/'), (3, 'Men', 2, '/1/2/3/'), (4, 'Women', 2, '/1/2/4/'),
 (5, 'Shirts', 3, '/1/2/3/5/'), (6, 'Food', 1, '/1/6/'), (7, 'Tea', 6, '/1/6/7/');
WITH RECURSIVE sub(id, name, depth) AS (
  SELECT id, name, 0 FROM cat WHERE id = 2
  UNION ALL SELECT c.id, c.name, sub.depth + 1 FROM cat c JOIN sub ON c.parent_id = sub.id)
SELECT depth, name FROM sub ORDER BY depth, name;
depth  name
-----  -------
    0  Clothes
    1  Men
    1  Women
    2  Shirts
(4 rows)
CREATE TABLE cat (id INTEGER PRIMARY KEY, name TEXT, parent_id INTEGER REFERENCES cat (id), path TEXT);
INSERT INTO cat VALUES
 (1, 'Shop', NULL, '/1/'), (2, 'Clothes', 1, '/1/2/'), (3, 'Men', 2, '/1/2/3/'), (4, 'Women', 2, '/1/2/4/'),
 (5, 'Shirts', 3, '/1/2/3/5/'), (6, 'Food', 1, '/1/6/'), (7, 'Tea', 6, '/1/6/7/');
WITH RECURSIVE sub(id, name, depth) AS (
  SELECT id, name, 0 FROM cat WHERE id = 2
  UNION ALL SELECT c.id, c.name, sub.depth + 1 FROM cat c JOIN sub ON c.parent_id = sub.id)
SELECT depth, name FROM sub ORDER BY depth, name;
depth  name
-----  -------
    0  Clothes
    1  Men
    1  Women
    2  Shirts
(4 rows)

The query starts at Clothes, then repeatedly adds children of rows already found. A breadcrumb (the path from a row up to the root) walks the other way:

WITH RECURSIVE up(id, name, parent_id) AS (
  SELECT id, name, parent_id FROM cat WHERE id = 5
  UNION ALL SELECT c.id, c.name, c.parent_id FROM cat c JOIN up ON c.id = up.parent_id)
SELECT name FROM up;
name
-------
Shirts
Men
Clothes
Shop
(4 rows)
WITH RECURSIVE up(id, name, parent_id) AS (
  SELECT id, name, parent_id FROM cat WHERE id = 5
  UNION ALL SELECT c.id, c.name, c.parent_id FROM cat c JOIN up ON c.id = up.parent_id)
SELECT name FROM up;
name
-------
Shirts
Men
Clothes
Shop
(4 rows)
WITH RECURSIVE up(id, name, parent_id) AS (
  SELECT id, name, parent_id FROM cat WHERE id = 5
  UNION ALL SELECT c.id, c.name, c.parent_id FROM cat c JOIN up ON c.id = up.parent_id)
SELECT name FROM up;
name
-------
Shirts
Men
Clothes
Shop
(4 rows)

Good: trivial to store; moving a branch changes one row; the foreign key keeps it valid. Weak: needs recursive queries (older or simpler systems may lack them; check yours).

Quick check: In a category tree where each row stores only its parent's id, what is the difficulty when you want all descendants of one row?

A plain join only reaches one level at a time; getting every level needs a recursive query (a recursive common table expression) or a different storage design.

2. Materialized path

Store the full path from the root as text in the row itself (the path column above, /1/2/3/5/ means root 1, then 2, then 3, then 5).

SELECT name FROM cat WHERE path LIKE '/1/2/%' ORDER BY path;
SELECT name FROM cat WHERE '/1/2/3/5/' LIKE path || '%' ORDER BY length(path);
SELECT name, length(path) - length(replace(path, '/', '')) - 1 AS depth FROM cat WHERE id = 5;
name
-------
Clothes
Men
Shirts
Women
(4 rows)

name
-------
Shop
Clothes
Men
Shirts
(4 rows)

name    depth
------  -----
Shirts      4
(1 row)
SELECT name FROM cat WHERE path LIKE '/1/2/%' ORDER BY path;
SELECT name FROM cat WHERE '/1/2/3/5/' LIKE path || '%' ORDER BY length(path);
SELECT name, length(path) - length(replace(path, '/', '')) - 1 AS depth FROM cat WHERE id = 5;
name
-------
Clothes
Men
Shirts
Women
(4 rows)

name
-------
Shop
Clothes
Men
Shirts
(4 rows)

name    depth
------  -----
Shirts      4
(1 row)
SELECT name FROM cat WHERE path LIKE '/1/2/%' ORDER BY path;
SELECT name FROM cat WHERE '/1/2/3/5/' LIKE path || '%' ORDER BY length(path);
SELECT name, length(path) - length(replace(path, '/', '')) - 1 AS depth FROM cat WHERE id = 5;
name
-------
Clothes
Men
Shirts
Women
(4 rows)

name
-------
Shop
Clothes
Men
Shirts
(4 rows)

name    depth
------  -----
Shirts      4
(1 row)

The first result is the whole Clothes branch with no recursion (an index on path helps prefix searches in many systems). The second is the ancestors of Shirts. The third counts slashes to get the depth (4 levels). Cost: moving a branch means rewriting the path of every row below it, and nothing stops the path and the parent from disagreeing, so change both in one transaction (lesson 6.2):

BEGIN;
UPDATE cat SET parent_id = 6 WHERE id = 3;
UPDATE cat SET path = replace(path, '/1/2/3/', '/1/6/3/') WHERE path LIKE '/1/2/3/%';
COMMIT;
SELECT name, path FROM cat WHERE id IN (3, 5) ORDER BY id;
name    path
------  ---------
Men     /1/6/3/
Shirts  /1/6/3/5/
(2 rows)
BEGIN;
UPDATE cat SET parent_id = 6 WHERE id = 3;
UPDATE cat SET path = replace(path, '/1/2/3/', '/1/6/3/') WHERE path LIKE '/1/2/3/%';
COMMIT;
SELECT name, path FROM cat WHERE id IN (3, 5) ORDER BY id;
name    path
------  ---------
Men     /1/6/3/
Shirts  /1/6/3/5/
(2 rows)
BEGIN;
UPDATE cat SET parent_id = 6 WHERE id = 3;
UPDATE cat SET path = replace(path, '/1/2/3/', '/1/6/3/') WHERE path LIKE '/1/2/3/%';
COMMIT;
SELECT name, path FROM cat WHERE id IN (3, 5) ORDER BY id;
name    path
------  ---------
Men     /1/6/3/
Shirts  /1/6/3/5/
(2 rows)

Men (with Shirts below it) now sits under Food.

3. Nested sets

Number the tree by walking around it: each node gets a left number when you enter it and a right number when you leave. A node's descendants are exactly the rows whose numbers lie between its left and right.

CREATE TABLE ns (id INTEGER PRIMARY KEY, name TEXT, lft INTEGER, rgt INTEGER);
INSERT INTO ns VALUES (1, 'Shop', 1, 14), (2, 'Clothes', 2, 9), (3, 'Men', 3, 6), (5, 'Shirts', 4, 5), (4, 'Women', 7, 8), (6, 'Food', 10, 13), (7, 'Tea', 11, 12);
SELECT c.name FROM ns c, ns p WHERE p.name = 'Clothes' AND c.lft BETWEEN p.lft AND p.rgt ORDER BY c.lft;
SELECT (rgt - lft - 1) / 2 AS below_shop FROM ns WHERE name = 'Shop';
name
-------
Clothes
Men
Shirts
Women
(4 rows)

below_shop
----------
         6
(1 row)
CREATE TABLE ns (id INTEGER PRIMARY KEY, name TEXT, lft INTEGER, rgt INTEGER);
INSERT INTO ns VALUES (1, 'Shop', 1, 14), (2, 'Clothes', 2, 9), (3, 'Men', 3, 6), (5, 'Shirts', 4, 5), (4, 'Women', 7, 8), (6, 'Food', 10, 13), (7, 'Tea', 11, 12);
SELECT c.name FROM ns c, ns p WHERE p.name = 'Clothes' AND c.lft BETWEEN p.lft AND p.rgt ORDER BY c.lft;
SELECT (rgt - lft - 1) / 2 AS below_shop FROM ns WHERE name = 'Shop';
name
-------
Clothes
Men
Shirts
Women
(4 rows)

below_shop
----------
         6
(1 row)
CREATE TABLE ns (id INTEGER PRIMARY KEY, name TEXT, lft INTEGER, rgt INTEGER);
INSERT INTO ns VALUES (1, 'Shop', 1, 14), (2, 'Clothes', 2, 9), (3, 'Men', 3, 6), (5, 'Shirts', 4, 5), (4, 'Women', 7, 8), (6, 'Food', 10, 13), (7, 'Tea', 11, 12);
SELECT c.name FROM ns c, ns p WHERE p.name = 'Clothes' AND c.lft BETWEEN p.lft AND p.rgt ORDER BY c.lft;
SELECT (rgt - lft - 1) / 2 AS below_shop FROM ns WHERE name = 'Shop';
name
-------
Clothes
Men
Shirts
Women
(4 rows)

below_shop
----------
         6
(1 row)

Reading a branch is one simple range test, and the number of descendants is arithmetic (the second query gives 6 below Shop). Cost: inserting or moving a node means renumbering many rows, so nested sets suit trees that are read often and rarely change.

4. Choosing

Adjacency list Materialized path Nested sets
Store parent id path text two numbers
Read a branch recursive query prefix search range test
Read ancestors recursive query prefix test range test
Move a branch change 1 row rewrite many paths renumber many rows
Keeps itself valid yes (foreign key) no no
Good for frequent edits, small trees menus, folders, read-heavy rarely edited, count-heavy

Worked example: a shop menu

The shop menu has 200 categories, changes a few times a month, and is shown on every page with a breadcrumb. Reading dominates, and editing is rare but must not break anything. A good choice: the adjacency list as the source of truth (the foreign key protects it), plus a path column rebuilt in the same transaction whenever the tree changes, used for fast branch and breadcrumb reads. The categories are made up.

Common mistakes

  • Letting path and parent_id disagree. Update both in one transaction.
  • Cycles in an adjacency list (A is the parent of B and B of A) make recursive queries run forever. Validate edits.
  • Using LIKE prefixes without delimiters: with ids 1 and 12, a path /1 also matches /12. Keep the trailing slash (as above).
  • Over-engineering a tree of twenty rows.

Key takeaways

  • A tree can be stored as parent links, as paths, or as nested-set numbers.
  • Parent links are simplest and easiest to edit; recursive queries read them.
  • Paths read branches without recursion, but moving rewrites many rows.
  • Nested sets read fast with ranges but are costly to change.
  • Choose by how often you read and how often you edit.

Practice

1. What does WITH RECURSIVE let you do?

Show answer

Repeat a step, starting from some rows and adding rows related to those already found, so a whole branch or path up a tree can be read in one query.

2. In the path /1/2/3/5/, who are the ancestors of node 5?

Show answer

Nodes 1, 2 and 3.

3. Why keep the trailing slash in paths?

Show answer

So a prefix test on /1/ cannot accidentally match /12/.

4. Which design makes moving a branch cheapest, and why?

Show answer

The adjacency list: only the moved node's parent_id changes.

5. In the nested sets table, how many descendants does a node with lft = 3 and rgt = 6 have?

Show answer

(6 - 3 - 1) / 2 = 1.

6. A forum has threaded comments, edited rarely and shown with all replies. Which design would you try first?

Show answer

Either a path or the adjacency list with a recursive query; both read a whole thread easily and moves are rare. Justify the choice by read pattern.