Fibonacci Spiral in SQL!

I came across a challenge on Dev.to (awesome site if you’re not already on it).

The challenge was to generate the Fibonacci Spiral in whatever language you use. This is fairly easy in languages such as JavaScript, Ruby and other traditional logic-based languages. But I was able to come up with a way of completing the challenge using SQL.

with FIBONACCI (i, SPIRAL, PREV) as
   (
      select
         1 i, 0 SPIRAL, cast(null as number) PREV
      from
         DUAL
      union all
      select
         f1.i + 1 i, f1.SPIRAL+ nvl(f1.PREV,1) SPIRAL, f1.SPIRAL PREV
      from
         FIBONACCI f1
      where
         f1.i < 20
   )


select
   SPIRAL
from
   FIBONACCI
order by i;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s