Generate Fibonacci Sequence (Recursive CTE)
Preview mode. Log in to edit, run, submit, and save progress.
Generate Fibonacci Sequence (Recursive CTE)
Write a SQL query using a recursive CTE - with no input tables - to generate the first 10 terms of the Fibonacci sequence. The sequence starts at position 1 with value 0, then 1, 1, 2, 3, 5, 8, 13, 21, 34. Return two columns: position (1-indexed) and fibonacci_value, ordered by position. No input tables are needed for this problem.
Examples
Use a recursive CTE that carries two running values a and b. At each step, the new (a, b) becomes (b, a+b). The anchor row starts with n=1, a=0, b=1. Recurse while n < 10.
Approach hint
Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.
Common mistake
Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.