Fibonacci Sequence via Recursive CTE
Preview mode. Log in to edit, run, submit, and save progress.
Medium
Fibonacci Sequence via Recursive CTE
Using only SQL, generate the first N Fibonacci numbers using a recursive CTE. The sequence starts at F(1)=0, F(2)=1, F(3)=1, F(4)=2, ... You are given a table FibInput with a single row containing N. Return (position, fibonacci_number) for positions 1 through N, ordered by position. Table: FibInput
| Column Name | Type | Description |
|---|---|---|
| n | INT | Number of Fibonacci values to generate |
Examples
Example 1
Use a recursive CTE carrying (n, a, b) where each step yields a and advances to (n+1, b, a+b). Terminate when n equals the value from FibInput.
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.
query.sql