Recursive CTE Depth Cap Guard
Cap runaway recursion with a depth counter in the recursive term: rows past the cap stop propagating, bounding the walk on bad data.
Code
CREATE TABLE nodes (
id int PRIMARY KEY,
parent_id int,
name text NOT NULL
);
INSERT INTO nodes VALUES
(1, NULL, 'root'),
(2, 1, 'child-a'),
(3, 2, 'grandchild'),
(4, 3, 'great-grandchild');
-- 深度上限熔断:到达上限的行不再向更深处扩展
-- 层级不明的陌生数据先设保守上限,防止意外深树拖垮查询
WITH RECURSIVE walk AS (
SELECT id, parent_id, name, 1 AS depth
FROM nodes
WHERE parent_id IS NULL
UNION ALL
SELECT n.id, n.parent_id, n.name, w.depth + 1
FROM nodes n
JOIN walk w ON n.parent_id = w.id
WHERE w.depth < 3 -- 上限:depth 到 3 就不再展开
)
SELECT name, depth FROM walk ORDER BY depth, name;
-- 对照:不加上限时同一棵树展开到第 4 层
WITH RECURSIVE walk AS (
SELECT id, parent_id, name, 1 AS depth
FROM nodes WHERE parent_id IS NULL
UNION ALL
SELECT n.id, n.parent_id, n.name, w.depth + 1
FROM nodes n JOIN walk w ON n.parent_id = w.id
)
SELECT max(depth) AS uncapped_depth FROM walk;
DROP TABLE nodes;How the snippet works
Several statements share this file — SELECT / INSERT / CREATE, with nodes and walk among the objects involved.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; a WHERE clause narrowing which rows one statement affects; MAX aggregation; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
What to watch for
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Applying it
Run the statement against the nodes table.
Statements that matter
WITH RECURSIVE walk AS (
SELECT id, parent_id, name, 1 AS depth
FROM nodes
WHERE parent_id IS NULL
UNION ALL
SELECT n.id, n.parent_id, n.name, w.depth + 1
FROM nodes n
JOIN walk w ON n.parent_id = w.id
WHERE w.depth < 3 -- 上限:depth 到 3 就不再展开
)
SELECT name, depth FROM walk ORDER BY depth, name;
WITH RECURSIVE walk AS (
SELECT id, parent_id, name, 1 AS depth
FROM nodes WHERE parent_id IS NULL
UNION ALL
SELECT n.id, n.parent_id, n.name, w.depth + 1
FROM nodes n JOIN walk w ON n.parent_id = w.id
)
SELECT max(depth) AS uncapped_depth FROM walk;
INSERT INTO nodes VALUES
(1, NULL, 'root'),
(2, 1, 'child-a'),
(3, 2, 'grandchild'),
(4, 3, 'great-grandchild');
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- The references are `nodes`, `walk`, with 2 joins tying them together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.