Challenge - 5 Problems
Recursive CTE Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple recursive CTE
Given the following SQL query using a recursive CTE, what will be the output?
SQL
WITH RECURSIVE numbers AS ( SELECT 1 AS n UNION ALL SELECT n + 1 FROM numbers WHERE n < 3 ) SELECT * FROM numbers ORDER BY n;
Attempts:
2 left
💡 Hint
Think about how the recursive part adds rows until the condition is false.
✗ Incorrect
The CTE starts with 1, then recursively adds 1 until n reaches 3, so the output is 1, 2, 3.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in recursive CTE
Which option contains a syntax error in the recursive CTE definition?
Attempts:
2 left
💡 Hint
Look carefully at the recursive SELECT statement syntax.
✗ Incorrect
Option A is missing the FROM keyword before cte, causing a syntax error.
❓ optimization
advanced2:00remaining
Optimizing recursive CTE to prevent infinite loops
Which option correctly prevents an infinite loop in this recursive CTE?
SQL
WITH RECURSIVE cte AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM cte WHERE num < 1000 ) SELECT * FROM cte;
Attempts:
2 left
💡 Hint
Think about how the recursion stops.
✗ Incorrect
The WHERE clause in the recursive part stops recursion when num reaches 1000, preventing infinite loops.
🧠 Conceptual
advanced2:00remaining
Understanding recursive CTE base and recursive parts
In a recursive CTE, what is the role of the base query and the recursive query?
Attempts:
2 left
💡 Hint
Think about how recursion builds results step by step.
✗ Incorrect
The base query starts the recursion with initial rows; the recursive query repeatedly adds rows until a condition stops it.
🔧 Debug
expert3:00remaining
Debugging unexpected output in recursive CTE
Given this recursive CTE, why does it produce duplicate rows?
SQL
WITH RECURSIVE cte AS ( SELECT 1 AS val UNION ALL SELECT val + 1 FROM cte WHERE val < 3 UNION ALL SELECT val + 1 FROM cte WHERE val < 3 ) SELECT * FROM cte ORDER BY val;
Attempts:
2 left
💡 Hint
Look at how many recursive SELECTs are combined.
✗ Incorrect
Having two UNION ALL recursive parts adds the same rows twice, causing duplicates.