Deriving the Golden Ratio in SQL

Raghav Rama
3 min readJan 2, 2023

--

Recently I gave my SQL final and realized despite having experience working on it, there are still things I can do better. To bridge that gap and potentially help others along the way I am sharing across a few SQL puzzles that I think are worth going through.

What is the Golden Ratio?

Photo by Vinsen Cekrani on Unsplash

The Golden Ratio aka the golden number is a ratio between 2 numbers that approximately equals to 1.618. It was written about by Euclid in “Elements” around 300 B.C., by Luca Pacioli, a contemporary of Leonardo Da Vinci, in “De Divina Proportione” in 1509, by Johannes Kepler around 1600 and by Dan Brown in 2003 in his best-selling novel, “The Da Vinci Code.” With the movie release of the “The Da Vinci Code”, the quest to know Phi was brought even more into the mainstream of pop culture.

This number/ratio has appeared in theology, mathematics, life, the universe, art and design. In this article I am going to see how the Fibonacci series actually can be used to derive this number.

Deriving the Fibonacci sequence in SQL

To derive the sequence, we would need the first two integers — 0, 1. We can do this in two ways either create a database containing one table with 2 rows for 0,1 or just create a temp table with 0 and 1. I will be doing the later as it is personally less code intensive.

Now the next number in the series will be determined by the number of the preceding 2 numbers, in this case that would be 0+1 = 1 and then we would have a series that would look like 0,1,1. The fourth term in the series would be the sum of the 2nd and 3rd terms — 1+1 = 2, making the sequence 0,1,1,2. We can create the sequence using recursive CTEs, which can go endlessly so let’s cap this to 100.

Now that we have the Fibonacci Sequence generated, we can derive the golden ratio by dividing the succeeding number by the preceding number which in this first case would be undefined, since 1/0 is not defined.

As we can see the ratio is approximates to 1.618 as the sequence goes on. I have rounded up the number to the nearest 3 decimal places for ease of interpretation but as the sequence goes on this approximation gets even closer to 1.618.

The code can be found here.

References:

  1. The Golden Ratio
  2. Joe Celko’s Advanced SQL Programming

--

--

Raghav Rama
Raghav Rama

Written by Raghav Rama

Sometimes you gotta run before you can walk.

No responses yet