Complete the code to start the recursive CTE by selecting the root node with id 1.
WITH RECURSIVE graph_path AS (
SELECT id, parent_id FROM nodes WHERE id = [1]
UNION ALL
SELECT n.id, n.parent_id FROM nodes n
JOIN graph_path gp ON n.parent_id = gp.id
)
SELECT * FROM graph_path;The recursive CTE starts from the root node with id 1, so the initial SELECT filters WHERE id = 1.
Complete the code to join the recursive CTE with the nodes table on the correct columns.
WITH RECURSIVE graph_path AS ( SELECT id, parent_id FROM nodes WHERE id = 1 UNION ALL SELECT n.id, n.parent_id FROM nodes n JOIN graph_path gp ON n.[1] = gp.id ) SELECT * FROM graph_path;
The join condition is n.parent_id = gp.id to find children of the current node.
Fix the error in the recursive CTE by completing the anchor member to select id and parent_id.
WITH RECURSIVE graph_path AS ( SELECT [1] FROM nodes WHERE id = 1 UNION ALL SELECT n.id, n.parent_id FROM nodes n JOIN graph_path gp ON n.parent_id = gp.id ) SELECT * FROM graph_path;
The anchor member must select both id and parent_id to match the recursive member's columns.
Fill both blanks to add a depth column starting at 0 and incrementing by 1 in recursion.
WITH RECURSIVE graph_path AS ( SELECT id, parent_id, 0 AS [1] FROM nodes WHERE id = 1 UNION ALL SELECT n.id, n.parent_id, gp.[2] + 1 FROM nodes n JOIN graph_path gp ON n.parent_id = gp.id ) SELECT * FROM graph_path;
The depth column tracks how far each node is from the root. It starts at 0 and increments by 1 each recursion.
Fill all three blanks to filter nodes with depth less than 3 and select id, parent_id, and depth.
WITH RECURSIVE graph_path AS ( SELECT id, parent_id, 0 AS depth FROM nodes WHERE id = 1 UNION ALL SELECT n.id, n.parent_id, gp.depth + 1 FROM nodes n JOIN graph_path gp ON n.parent_id = gp.id WHERE gp.depth [1] [2] [3] ) SELECT id, parent_id, depth FROM graph_path;
The WHERE clause limits recursion to nodes with depth less than or equal to 3, so depth <= 3.