Loops in BigQuery

Learn how to use BigQuery scripting to calculate Fibonacci numbers with for loops

Bence Komarniczky
Towards Data Science
4 min readJul 7, 2020

--

Ever wanted to loop around stuff in SQL? Well, you can with scripting. Let’s see how we can calculate Fibonacci numbers in BigQuery with loops.

Do the loop in BigQuery! — Photo by Claire Satera on Unsplash

I previously showed how to do Fibonacci in BigQuery with JavaScript UDFs (user-defined functions) and also talked about arrays in BigQuery so if you’re new to BigQuery, check those out first.

Basics of Scripting

Before we begin calculating Fibonacci numbers, let’s talk about the building blocks of SQL scripting. In programming languages (such as Python) it’s quite natural to set variables with some values and then work with those variables, whereas in SQL you usually start out with some data lurking around in tables.

For full access to all Medium articles — including mine — consider subscribing here.

With SQL scripting you can declare variables and then use them in calculations, do for loops etc. The gotchas (for those coming from dynamically typed languages) is that you need to declare the type of each variable before you start using them and those types can never ever change.

With SQL scripting you can…

--

--

Data scientist building ML products in ad-tech. I write tutorials on data science🧑‍🔬, machine learning 🤖, Julia and cloud computing ☁️.