Last active
June 12, 2020 16:19
-
-
Save lovasoa/ff0ee1836b9b80de7f915e8348eebe78 to your computer and use it in GitHub Desktop.
Computing the fibonacci sequence in SQL (with SQLite)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Computing the fibonaccci sequence in SQL | |
-- Using a common table expression | |
-- see: https://www.sqlite.org/lang_with.html | |
with recursive fibonacci (n, current, next) as ( | |
select 0, 0, 1 -- n=0, current=fibonacci(0)=0, next=fibonacci(1)=1 | |
union all -- Using a recursive union between the fibonacci table and itself | |
select n+1 as n, next, next+current -- n=n+1, current=next, next+=current | |
from fibonacci | |
) | |
select | |
n, current as `fibonacci(n)` | |
from fibonacci | |
limit 10 -- since the fibonacci table is infinite, we have to limit what we select |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment