Closure Table Precomputes Subtree Queries

Materialize ancestor-to-descendant pairs once into a closure table, then subtree and size queries become plain joins with no recursion.

SqlData Fetching

Code

snippet
-- 闭包表:把"祖先 → 后代"的传递闭包物化成行,递归只发生在这里
-- ancestor = descendant 的行表示节点自身
CREATE TEMP TABLE folders (
    id        int PRIMARY KEY,
    name      text NOT NULL,
    parent_id int REFERENCES folders(id)
);
CREATE TEMP TABLE folder_closure (
    ancestor   int NOT NULL,
    descendant int NOT NULL,
    depth      int NOT NULL,
    PRIMARY KEY (ancestor, descendant)
);
INSERT INTO folders VALUES
    (1, 'docs', NULL), (2, 'work', 1), (3, 'tax', 2), (4, 'photos', 1);

INSERT INTO folder_closure
WITH RECURSIVE walk AS (
    SELECT id AS ancestor, id AS descendant, 0 AS depth FROM folders
    UNION ALL
    SELECT w.ancestor, f.id, w.depth + 1
    FROM walk w JOIN folders f ON f.parent_id = w.descendant
)
SELECT ancestor, descendant, depth FROM walk;

-- 之后的查询都是普通连接:整棵子树、按层排序
SELECT f.id, f.name, c.depth
FROM folder_closure c JOIN folders f ON f.id = c.descendant
WHERE c.ancestor = 1
ORDER BY c.depth, f.id;

-- 子树规模:每个祖先的后代计数
SELECT ancestor, COUNT(*) AS subtree_size
FROM folder_closure
GROUP BY ancestor
ORDER BY ancestor;

The path through the file

The file runs SELECT / INSERT / CREATE statements, touching folders, folder_closure and walk.

folders and folder_closure are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION joining up the outputs of separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard fastening child rows to their parent table.

Applying it

The file sets up its own scratch surface: it builds the session-local tables it works with (folders, folder_closure), so one full run against a throwaway database is enough.

Statements that matter

INSERT INTO folder_closure
WITH RECURSIVE walk AS (
    SELECT id AS ancestor, id AS descendant, 0 AS depth FROM folders
    UNION ALL
    SELECT w.ancestor, f.id, w.depth + 1
    FROM walk w JOIN folders f ON f.parent_id = w.descendant
)
SELECT ancestor, descendant, depth FROM walk;
SELECT f.id, f.name, c.depth
FROM folder_closure c JOIN folders f ON f.id = c.descendant
WHERE c.ancestor = 1
ORDER BY c.depth, f.id;
SELECT ancestor, COUNT(*) AS subtree_size
FROM folder_closure
GROUP BY ancestor
ORDER BY ancestor;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `folders`, `folder_closure`, `walk`, with 2 joins tying them together.