Fibonacci sequence using WITH RECURSIVE

-- Fibonacci sequence
-- Example to demo WITH RECURSIVE in PostgreSQL 8.4
with recursive f as (
    select 0 as a, 1 as b
    union all
    select b as a, a+b from f where a < 100
) select a from f;

Results in:

  a 
-----
   0
   1
   1
   2
   3
   5
   8
  13
  21
  34
  55
  89
 144
(13 rows)

Kommentarer
Postat av:

The blog (http://planetpostgresql.org/, not http://planet.postgresql.org/) contains an error: change "where a 100" to "where a < 100".

Regards, Andreas

2009-03-04 @ 21:05:50
Postat av: roppert

@Andreas: Thanks for noticing. I'm afraid it's out of my reach though since both planets use the same RSS feed and it's properly encoded.

2009-03-04 @ 21:16:39
Postat av: Ian

And it's fun to play with to overflow numeric types...

with f as (
select cast(0 as float) as a, cast(1 as float) as b
union all
select b as a, a+b from f
) select a, b from f;

2009-03-05 @ 22:26:12
Postat av: roppert

@Ian: hehe, yeah:

robertg=# with recursive f as (
select cast(0 as float) as a, cast(1 as float) as b
union all
select b as a, a+b from f
) select a, b from f;
ERROR: value out of range: overflow
robertg=#

2009-03-05 @ 22:35:54

Kommentera inlägget här:

Namn:
Kom ihåg mig?

E-postadress: (publiceras ej)

URL/Bloggadress:

Kommentar:

Trackback
RSS 2.0