Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active June 12, 2020 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovasoa/ff0ee1836b9b80de7f915e8348eebe78 to your computer and use it in GitHub Desktop.
Save lovasoa/ff0ee1836b9b80de7f915e8348eebe78 to your computer and use it in GitHub Desktop.
Computing the fibonacci sequence in SQL (with SQLite)
-- 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