Fibonacci Numbers

From PostgreSQL wiki

Jump to: navigation, 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;
$$;
Personal tools