Fibonacci Numbers

From PostgreSQL wiki
Jump to navigationJump to search

Fun Snippets

Fibonacci Numbers

Works with PostgreSQL

>=8.4

Written in

SQL

Depends on

Nothing


Create a fibonnaci sequence to the limiting number given

CREATE OR REPLACE FUNCTION fib(f integer) 
RETURNS SETOF integer
LANGUAGE SQL
AS $$
WITH RECURSIVE t(a,b) AS (
        VALUES(0,1)
    UNION ALL
        SELECT greatest(a,b), a + b as a from t
        WHERE b < $1
   )
SELECT a FROM t;
$$;