Not so long ago I wrote about implementing GCD function in PostgreSQL using CTE.
Here I will show how Fibonacci Numbers may be obtained using the same technique.
So to have first 16 members of this sequence we should execute something like this:
WITH RECURSIVE t(a, b) AS ( VALUES (1, 1) UNION ALL SELECT b, a + b FROM t ) SELECT a FROM t LIMIT 16; |
Suppose we should add this code to Wiki Library Snippets. Any objections?
UPD. Some others unnatural ways to calculate Fibonacci numbers may be found in Russian.
Advertisement
June 21, 2010 at 12:16 pm
[...] under Coding | Tags: CTE, fibonacci, PostgreSQL, SQL, trick | Leave a Comment Suppose my previous Fibonacci code should be a function. Here it [...]
June 21, 2010 at 5:53 pm
Should it be “VALUES (1, 2)” instead of “VALUES (1, 1)”?
June 21, 2010 at 6:07 pm
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
June 21, 2010 at 7:50 pm
Yeah, after searching a while I found the same answer. Thanks and sorry.
February 1, 2012 at 12:42 pm
[...] so long ago I used Common Table Expressions for Fibonacci Numbers [...]