Interview Questions/SQL/Fibonacci Sequence via Recursive CTE

Fibonacci Sequence via Recursive CTE

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

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 NameTypeDescription
nINTNumber of Fibonacci values to generate

Database Schema (Inferred)

FibInput

Column NameExample Value
n10

Example

FibInput

n
10

Output

positionfibonacci_number
10
21
31
42
53
65
78
813
921
1034

Explanation:

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.

SQL Editor
Loading...

FibInput

n
10

Output

positionfibonacci_number
10
21
31
42
53
65
78
813
921
1034