Interview Questions/SQL/Generate Fibonacci Sequence (Recursive CTE)

Generate Fibonacci Sequence (Recursive CTE)

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

Medium

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

positionfibonacci_value
10
21
31
42
53
65
78
813
921
1034

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.

SQL Editor
Loading...

Output

positionfibonacci_value
10
21
31
42
53
65
78
813
921
1034