Video in progress
How does a recursive CTE work, and what are its risks on tree-like data?
A recursive CTE starts from the result of the initial (anchor) query and runs the recursive part again and again until no new rows come out. The main risks are an endless loop because of a cycle in the data, and slowness on a large tree.
📖 Answer
For example, a category and all of its subcategories:
WITH RECURSIVE tree AS (
SELECT id, parent_id, name, 1 AS depth, ARRAY[id] AS path
FROM category WHERE id = 5 -- anchor
UNION ALL
SELECT c.id, c.parent_id, c.name, t.depth + 1, t.path || c.id
FROM category c
JOIN tree t ON c.parent_id = t.id
WHERE NOT c.id = ANY(t.path) -- protection against cycles
AND t.depth < 20
)
SELECT * FROM tree;
Internally it's iterative: at each step only the previous step's result is the "working table". UNION (without ALL) removes duplicates and partly stops a cycle, but protecting with a path is more reliable. Since PG14 there is also the CYCLE id SET is_cycle USING path syntax.
For performance, an index on parent_id is a must, since every step joins on that column.
If the tree is read very often and changes rarely, the alternatives are a materialized path (/1/5/17/), the ltree extension, or a closure table. They speed up reads but make moving nodes more complicated.
One note: up to PG12, any CTE was an "optimization fence". Since PG12 a plain CTE (non-recursive, used once) is inlined; if needed you can force materialization with MATERIALIZED.
Sign up to mark studied questions and save your progress.