Challenge - 5 Problems
Recursive CTE Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Find all reachable nodes from node 1
Given the table
edges with columns source and target, what is the output of this recursive CTE query that finds all nodes reachable from node 1?PostgreSQL
WITH RECURSIVE reachable AS ( SELECT source, target FROM edges WHERE source = 1 UNION SELECT e.source, e.target FROM edges e INNER JOIN reachable r ON e.source = r.target ) SELECT DISTINCT target FROM reachable ORDER BY target;
Attempts:
2 left
💡 Hint
Think about how the recursive part expands the reachable nodes starting from source 1.
✗ Incorrect
The base case selects edges starting at node 1. The recursive part joins on the target to find further reachable nodes. The distinct targets collected are nodes 2, 3, and 4.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in recursive CTE
Which option contains a syntax error in this recursive CTE that tries to find all nodes reachable from node 1?
PostgreSQL
WITH RECURSIVE reachable AS ( SELECT source, target FROM edges WHERE source = 1 UNION SELECT e.source, e.target FROM edges e JOIN reachable r ON e.source = r.target ) SELECT DISTINCT target FROM reachable ORDER BY target;
Attempts:
2 left
💡 Hint
Check if JOIN without INNER is valid in PostgreSQL.
✗ Incorrect
In PostgreSQL, JOIN is shorthand for INNER JOIN and is valid syntax. The query has no syntax errors.
❓ optimization
advanced2:00remaining
Optimize recursive CTE to avoid duplicates
Which option optimizes this recursive CTE to avoid revisiting nodes and duplicates in the result?
PostgreSQL
WITH RECURSIVE reachable(node) AS ( SELECT 1 UNION SELECT e.target FROM edges e JOIN reachable r ON e.source = r.node ) SELECT node FROM reachable ORDER BY node;
Attempts:
2 left
💡 Hint
Prevent revisiting nodes by filtering them out in recursion.
✗ Incorrect
Adding a WHERE clause to exclude already visited nodes prevents infinite loops and duplicates.
🧠 Conceptual
advanced2:00remaining
Understanding recursive CTE termination
What causes a recursive CTE for graph traversal to stop recursing?
Attempts:
2 left
💡 Hint
Think about how recursion ends naturally in SQL.
✗ Incorrect
The recursion stops when the recursive SELECT adds no new rows to the result set.
🔧 Debug
expert3:00remaining
Diagnose infinite recursion in recursive CTE
Given this recursive CTE, why does it cause infinite recursion or run indefinitely?
PostgreSQL
WITH RECURSIVE reachable(node) AS ( SELECT 1 UNION ALL SELECT e.target FROM edges e JOIN reachable r ON e.source = r.node ) SELECT node FROM reachable ORDER BY node;
Attempts:
2 left
💡 Hint
Consider what happens if the graph has loops.
✗ Incorrect
If the graph has cycles and the query does not exclude already visited nodes, recursion never ends.