Problem Statement
How do you prevent infinite loops and duplicates in a recursive CTE that walks a graph?
Explanation
Add a termination condition that stops expansion when there are no new edges to follow or a maximum depth is reached. In hierarchical data, stop when the parent is NULL or repeats.
Track visited nodes in the recursive member. Accumulate the path and exclude nodes already seen. This prevents cycles from re-entering the same vertex and emitting duplicates.
Code Solution
SolutionRead Only
WITH RECURSIVE walk AS ( SELECT id, parent_id, ARRAY[id] AS path FROM nodes WHERE parent_id IS NULL UNION ALL SELECT n.id, n.parent_id, path || n.id FROM nodes n JOIN walk w ON w.id = n.parent_id WHERE n.id <> ALL(w.path) ) SELECT * FROM walk;
