Hierarchies: adjacency lists and closure tables
Overview
An adjacency list stores one parent reference per node. A closure table stores ancestor–descendant pairs, including each node paired with itself at depth zero. The fixture is a small tree: root 1, children 2 and 3, and grandchild 4 under 2. A recursive CTE from V40 traverses the adjacency list; the closure table answers the same subtree query without recursion.
First example
WITH RECURSIVE tree(id,depth) AS ( SELECT id,0 FROM pro_node WHERE id=2 UNION ALL SELECT n.id,t.depth+1 FROM pro_node n JOIN tree t ON n.parent_id=t.id WHERE t.depth<10)SELECT id,depth FROM tree ORDER BY depth,id;Observed SQLite result (rows in JSON):
[ [ 2, 0 ], [ 4, 1 ]]How it works
Both examples return descendants of node 2 including itself. The recursive query is bounded and intended for the known acyclic tree. A depth cap is not proof of acyclicity; detect cycles explicitly for untrusted graphs. Moving a subtree requires updating all affected closure rows transactionally. A materialized path stores the path as a value and needs safe delimiter handling; nested sets use interval boundaries and may require many changes on insertion. Closure tables can grow quadratically in a chain. Choose based on read/write patterns; a parent foreign key alone does not forbid longer cycles.
Practical example
SELECT descendant,depth FROM pro_closure WHERE ancestor=2 ORDER BY depth,descendant;Observed SQLite result (rows in JSON):
[ [ 2, 0 ], [ 4, 1 ]]Practice and mistakes
Practice: change the starting node to 1 in both examples, predict four rows and compare. In a separate copy change parent of 4 to 3; explain why the closure table becomes stale unless rebuilt. Do not treat stored closure as independently authoritative.