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 Recursive CTE Generating Numbers 1 to 5
What is the output of this SQL query using a recursive CTE to generate numbers from 1 to 5?
SQL
WITH RECURSIVE numbers AS ( SELECT 1 AS num UNION ALL SELECT num + 1 FROM numbers WHERE num < 5 ) SELECT * FROM numbers ORDER BY num;
Attempts:
2 left
💡 Hint
Look at the base case and the stopping condition in the recursive part.
✗ Incorrect
The CTE starts at 1 and recursively adds 1 until it reaches 5, so the output is numbers 1 through 5 inclusive.
📝 Syntax
intermediate2:00remaining
Identify the Syntax Error in Recursive CTE
Which option contains a syntax error in this recursive CTE that generates numbers from 1 to 3?
SQL
WITH RECURSIVE nums AS ( SELECT 1 AS n UNION ALL SELECT n + 1 FROM nums WHERE n < 3 ) SELECT * FROM nums;
Attempts:
2 left
💡 Hint
Check if the keyword RECURSIVE is required for recursive CTEs.
✗ Incorrect
Option A misses the RECURSIVE keyword, which is required to define a recursive CTE in standard SQL.
❓ optimization
advanced3:00remaining
Optimizing Recursive CTE for Large Series
Which option is the most efficient way to generate numbers from 1 to 1000 using a recursive CTE?
Attempts:
2 left
💡 Hint
Check the stopping condition and whether the CTE is recursive.
✗ Incorrect
Option C correctly uses RECURSIVE keyword and stops at n < 1000, generating numbers 1 to 1000 efficiently. Option C skips numbers by 10, missing many numbers. Option C uses <= 1000 in recursion, causing one extra recursion step but still works. Option C misses RECURSIVE keyword causing syntax error.
🔧 Debug
advanced2:00remaining
Why Does This Recursive CTE Cause an Infinite Loop?
Consider this recursive CTE:
WITH RECURSIVE cte AS (
SELECT 1 AS val
UNION ALL
SELECT val + 1 FROM cte
)
SELECT * FROM cte WHERE val <= 5;
Why does this query cause an infinite loop or error?
Attempts:
2 left
💡 Hint
Look at the recursive SELECT and its WHERE clause.
✗ Incorrect
The recursive SELECT does not have a WHERE clause to stop recursion, so it keeps adding 1 forever causing infinite recursion or error.
🧠 Conceptual
expert2:30remaining
Understanding Recursive CTE Execution Order
In a recursive CTE, which part executes first and how does the recursion proceed?
Attempts:
2 left
💡 Hint
Think about how recursion builds results step by step.
✗ Incorrect
Recursive CTEs start with the anchor member to get initial rows, then repeatedly apply the recursive member to add more rows until no new rows appear.