Skip to content

Fibonacci sequence 🔢

Info

This is just for fun, there's no real-world application for this (as far as I know) 😝

Question

Generate the first 45 terms of the Fibonacci sequence.

The output should have one row per term in the sequence, with the columns:

  • n as the term number
  • f_n as the corresponding Fibonacci number

Order the output by n.

The Fibonacci sequence is defined as fn = fn-1 + fn-2, where f1 = f2 = 1.

For example:

  • The third term is f3 = f2 + f1 = 1 + 1 = 2
  • The fourth term is f4 = f3 + f2 = 2 + 1 = 3
  • ...
  • The tenth term is f10 = f9 + f8 = 34 + 21 = 55

The solution can be found at:


Sample input

Generate the first 10 terms of the Fibonacci sequence.

Sample output
n f_n
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
10 55
solution(n, f_n) as (
    values
        (1,  1),
        (2,  1),
        (3,  2),
        (4,  3),
        (5,  5),
        (6,  8),
        (7,  13),
        (8,  21),
        (9,  34),
        (10, 55)
)
Hint 1

Use a recursive CTE to generate the sequence.

Hint 2

Use the columns n, f_n, and f_m to keep track of the current term, the current Fibonacci number, and the previous Fibonacci number, respectively.