Generate Fibonacci Sequence (Recursive CTE)
Preview mode. Log in to edit, run, submit, and save progress.
Description
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.
Example
Output
| position | fibonacci_value |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 8 |
| 8 | 13 |
| 9 | 21 |
| 10 | 34 |
Explanation:
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.
Output
| position | fibonacci_value |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 3 |
| 6 | 5 |
| 7 | 8 |
| 8 | 13 |
| 9 | 21 |
| 10 | 34 |