Tag: fibonacci series in SQL Server

Fibonacci series in SQL Server

Today, I noticed that my elder kid was learning about fibonacci series. While observing her, I was just trying to write SQL script to produce the series just for fun and sharing it with you all.

What is fibonacci series?

A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc. Fibonacci was not the first to know about the sequence, it was known in India hundreds of years before! Leonardo Pisano Bogollo is known as fibonacci man, and he lived between 1170 and 1250 in Italy. “Fibonacci” was his nickname, which roughly means “Son of Bonacci”.

Fibonacci Day is November 23rd, as it has the digits “1, 1, 2, 3” (11 represents month number-23 represents day part) which is part of the sequence. So next Nov 23 let everyone know about this fact.(Honestly, I never noticed this until now.)

Formula & Code Implementation

The simple formula is Fn = Fn-1 + Fn-2

The code implementation as below :

I used Common Table Expression (CTE) to generate it easily over while loop. If you guys are comfortable with while loop, you can even generate with loop.

Declare @UntilNo integer = 100
;With Fibonacci (N, NextN) AS
 SELECT 0, 1
    SELECT NextN, NextN+ N
    FROM Fibonacci
    WHERE N < @UntilNo
SELECT Substring(
    (SELECT cast(', ' as varchar(max)) + cast(N as varchar(max)
FROM Fibonacci
FOR XML PATH('')),3,10000000) AS list

I’d like to grow my readership. If you enjoyed this blog post, please share it with your friends!