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.
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 declare variables and then use them in calculations, do for loops etc.
Let’s declare our first variable and print it to the console:
DECLARE uninteresting_number INT64;
SET uninteresting_number = 1729;
SELECT uninteresting_number;
The steps we did here are:
DECLARE
keyword instantiates our variable with a name uninteresting_number
and a type INT64
.SET
the value of the number to 1729.If you want to do the declaration and the setting of the variable in one go, you can use the
_DEFAULT_
argument as well:_DECLARE my_number INT64 DEFAULT 1729;_
.
If we want to update our variables then we use the SET
keyword again to do so:
DECLARE a INT64 DEFAULT 1;
DECLARE b INT64 DEFAULT 2;
DECLARE c INT64;
SET c = a;
SET c = c + b;
SELECT a, b, c;
The steps we did here are:
DECLARE
keyword instantiates our variable with a name uninteresting_number
and a type INT64
.SET
the value of the number to 1729.If you want to do the declaration and the setting of the variable in one go, you can use the
_DEFAULT_
argument as well:_DECLARE my_number INT64 DEFAULT 1729;_
.
If we want to update our variables then we use the SET
keyword again to do so:
DECLARE a INT64 DEFAULT 1;
DECLARE b INT64 DEFAULT 2;
DECLARE c INT64;
SET c = a;
SET c = c + b;
SELECT a, b, c;
Here, we first set c
to be equal to a
then we incremented c
by b
, to get the following:
#google-cloud-platform #sql #programming #bigquery #mathematics