This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing one user define function to generate Fibonacci Series in PostgreSQL.
Today Morning, I have started to take the interview for PostgreSQL Database Developer.
Generally, I am asking complex SQL Query, but this time I have asked to implement few mathematical logics like: “Write a small function to generate Fibonacci Series”.
Fibonacci Series means a series of numbers in which each number is the sum of the two preceding numbers.
e.g 1, 1, 2, 3, 5, 8, 13…
I am sharing this solution here, Database Developer should prepare yourself because Interviewer like, me can ask this kind of question.
Fibonacci Series Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
CREATE OR REPLACE FUNCTION fn_Fibonacci(FNum INTEGER) RETURNS SETOF INTEGER LANGUAGE SQL AS $dbrnd$ WITH RECURSIVE cte(Num1,Num2) AS ( VALUES(0,1) UNION ALL SELECT GREATEST(Num1,Num2),Num1 + Num2 AS FibonacciSeries FROM cte WHERE Num2 < FNum ) SELECT Num1 FROM cte; $dbrnd$; |
Execute Function to generate Fibonacci Series upto 50:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
SELECT *FROM fn_Fibonacci(50); fn_fibonacci -------------- 0 1 1 2 3 5 8 13 21 34 (10 rows) |