In this post we are going to cover branching and loops in Snowflake Scripting.
That is IF, CASE as a statement, and then three kinds of loop: FOR, WHILE and REPEAT. Every one of them is closed by its own name, so an IF ends with END IF and a FOR ends with END FOR.
We will start with the simplest IF there is and build it up step by step. Near the end we will find out what a loop leaves behind when it fails part way through, which is the most useful thing in this post.
Every loop you will see is hard bounded, so nothing here can run away. Every query was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 147 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with the simplest IF
- Now the middle branch, which is where people get caught
- Now three ways to break an IF
- Now let's use CASE as a statement
- What happens with no ELSE and nothing matching?
- Now let's loop over a range with FOR
- What happens when the bounds are the wrong way round?
- Now WHILE and REPEAT, with the same impossible condition
- And how do you stop a loop the condition will not stop?
- Now a loop that writes a row on every pass
- And now the one that matters: what survives a failure?
- One last thing: every block is closed by its own name
Let's create some sample data
Most of this post needs no data at all, because a loop can count on its own. What we do need, near the end, is somewhere for a loop to write a row on every pass, so that we can look at what it left behind.
-- Sample data for this post.
-- A table for the loops to write a row into on every pass.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE TRACE_T147 (
STEP INT,
NOTE VARCHAR(40)
);CREATE OR REPLACE TABLE TRACE_T147 (
STEP INT,
NOTE VARCHAR(40)
);| status |
|---|
| Table TRACE_T147 successfully created. |
That is the whole setup. Now let's branch.
Let's start with the simplest IF
The shape is IF, the condition in brackets, THEN, the statements, and END IF.
CREATE OR REPLACE PROCEDURE IFBASIC_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100) THEN
RETURN 'above a hundred';
ELSE
RETURN 'a hundred or less';
END IF;
END;
$$;| status |
|---|
| Function IFBASIC_T147 successfully created. |
Let's call it with a number that makes the condition true.
CALL IFBASIC_T147(250);| IFBASIC_T147 |
|---|
| above a hundred |
And with one that does not.
CALL IFBASIC_T147(50);| IFBASIC_T147 |
|---|
| a hundred or less |
Both sides work, and notice there is no ELSE in that body at all. The second RETURN is simply the next statement after the END IF, reached whenever the condition was false.
Now the middle branch, which is where people get caught
A three way branch needs an else-if, and Snowflake spells it as one word.
CREATE OR REPLACE PROCEDURE ELSEIF_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100) THEN
RETURN 'high';
ELSEIF (:N > 50) THEN
RETURN 'middle';
ELSE
RETURN 'low';
END IF;
END;
$$;| status |
|---|
| Function ELSEIF_T147 successfully created. |
CALL ELSEIF_T147(75);| ELSEIF_T147 |
|---|
| middle |
One word works, and the middle branch ran.
Now the spelling you would use in Oracle or PL/pgSQL.
CREATE OR REPLACE PROCEDURE ELSIF_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100) THEN
RETURN 'high';
ELSIF (:N > 50) THEN
RETURN 'middle';
ELSE
RETURN 'low';
END IF;
END;
$$;001003 (42000): SQL compilation error: syntax error line 5 at position 20 unexpected 'THEN'.
001003, and look at where it points: at the THEN that follows the condition. Snowflake read ELSIF as something else entirely and then met a word it was not expecting. That spelling is out.
And two words, written as ELSE IF
This one is created without a complaint, and it is the one worth slowing down for.
CREATE OR REPLACE PROCEDURE ELSESPACEIF_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100) THEN
RETURN 'high';
ELSE IF (:N > 50) THEN
RETURN 'middle';
ELSE
RETURN 'low';
END IF;
END IF;
END;
$$;| status |
|---|
| Function ELSESPACEIF_T147 successfully created. |
Read that body carefully, because it is not an else-if at all. There are two END IF lines at the bottom of it, and it needs both. What we have written is a second, complete IF nested inside the ELSE branch of the first one.
It is accepted, and it means something slightly different from the one word version. I did not capture a call of this one, so there is no result grid for it here and I am not going to tell you what it returns.
Now three ways to break an IF
First, leave out the THEN.
CREATE OR REPLACE PROCEDURE NOTHEN_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100)
RETURN 'above a hundred';
END IF;
RETURN 'a hundred or less';
END;
$$;001003 (42000): SQL compilation error: syntax error line 4 at position 8 unexpected 'RETURN'.
A syntax error at the RETURN, which is the first word that could not follow a condition.
Next, leave out the END IF.
CREATE OR REPLACE PROCEDURE NOENDIF_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (:N > 100) THEN
RETURN 'above a hundred';
RETURN 'a hundred or less';
END;
$$;001003 (42000): SQL compilation error: syntax error line 6 at position 3 unexpected ';'. syntax error line 7 at position 0 unexpected '<EOF>'.
This one complains twice, and the second complaint is the honest one: it ran out of input while still waiting for the block to be closed.
And last, the condition with no brackets around it.
CREATE OR REPLACE PROCEDURE NOBRACKETS_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF :N > 100 THEN
RETURN 'above a hundred';
END IF;
RETURN 'a hundred or less';
END;
$$;001003 (42000): SQL compilation error: syntax error line 3 at position 7 unexpected ':'. syntax error line 3 at position 16 unexpected 'THEN'.
A syntax error at the colon, because without the brackets Snowflake is not expecting a variable there at all. The brackets are not optional.
CALL NOBRACKETS_T147(250);002139 (02000): SQL compilation error: Unknown function NOBRACKETS_T147.
Which confirms it. The procedure was never created, so there is nothing to call.
Now let's use CASE as a statement
You already know CASE as an expression, where it produces a value. Inside a block it can also be a statement, where each branch holds statements and the whole thing ends with END CASE.
CREATE OR REPLACE PROCEDURE CASESTMT_T147(R VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
CASE (:R)
WHEN 'north' THEN
RETURN 'the north branch ran';
WHEN 'south' THEN
RETURN 'the south branch ran';
ELSE
RETURN 'the else branch ran';
END CASE;
END;
$$;| status |
|---|
| Function CASESTMT_T147 successfully created. |
CALL CASESTMT_T147('south');| CASESTMT_T147 |
|---|
| the south branch ran |
It picked the branch that matched and ran what was inside it.
And a value none of the branches match falls to the ELSE.
CALL CASESTMT_T147('nowhere');| CASESTMT_T147 |
|---|
| the else branch ran |
What happens with no ELSE and nothing matching?
Let's take the ELSE away and then call it with something that matches none of the branches.
CREATE OR REPLACE PROCEDURE CASENOELSE_T147(R VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
CASE (:R)
WHEN 'north' THEN
RETURN 'the north branch ran';
END CASE;
RETURN 'past the end of the case';
END;
$$;| status |
|---|
| Function CASENOELSE_T147 successfully created. |
CALL CASENOELSE_T147('nowhere');| CASENOELSE_T147 |
|---|
| past the end of the case |
No error at all. Execution simply carried on past the END CASE and reached the next statement.
This is worth knowing because in some languages an unmatched CASE with no ELSE raises an exception. Here it is a quiet no-op, which is friendlier and also easier to overlook.
There is a second form as well, with conditions in the branches instead of values to match.
CREATE OR REPLACE PROCEDURE CASESEARCHED_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
CASE
WHEN :N > 100 THEN
RETURN 'high';
WHEN :N > 50 THEN
RETURN 'middle';
ELSE
RETURN 'low';
END CASE;
END;
$$;| status |
|---|
| Function CASESEARCHED_T147 successfully created. |
CALL CASESEARCHED_T147(75);| CASESEARCHED_T147 |
|---|
| middle |
Both forms of the statement work. And a fair question: can a CASE expression and a CASE statement sit in the same body?
CREATE OR REPLACE PROCEDURE BOTHCASES_T147(N NUMBER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
LABEL_FROM_EXPRESSION VARCHAR;
BEGIN
SELECT CASE WHEN :N > 100 THEN 'big' ELSE 'small' END
INTO :LABEL_FROM_EXPRESSION;
CASE
WHEN :N > 100 THEN
RETURN 'statement says big, expression says ' || :LABEL_FROM_EXPRESSION;
ELSE
RETURN 'statement says small, expression says ' || :LABEL_FROM_EXPRESSION;
END CASE;
END;
$$;| status |
|---|
| Function BOTHCASES_T147 successfully created. |
CALL BOTHCASES_T147(250);| BOTHCASES_T147 |
|---|
| statement says big, expression says big |
They can, and they agree. The same keyword doing two different jobs, side by side in one body.
Now let's loop over a range with FOR
The shape is FOR, a name, IN, a range, DO, and END FOR.
CREATE OR REPLACE PROCEDURE FORRANGE_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
OUT_TEXT VARCHAR DEFAULT '';
BEGIN
FOR I IN 1 TO 4 DO
OUT_TEXT := :OUT_TEXT || :I || ' ';
END FOR;
RETURN 'visited: ' || :OUT_TEXT;
END;
$$;| status |
|---|
| Function FORRANGE_T147 successfully created. |
CALL FORRANGE_T147();| FORRANGE_T147 |
|---|
| visited: 1 2 3 4 |
It visited every value in the range, inclusive at both ends.
And notice that I was never declared anywhere. The loop makes its own.
So what if a variable of that name already exists?
Here is a block that declares I with a default of its own and then runs a loop using the same letter. It reports the loop values as it goes and then reports I again after the loop has finished.
CREATE OR REPLACE PROCEDURE FORUNDECLARED_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
I NUMBER DEFAULT 99;
OUT_TEXT VARCHAR DEFAULT '';
BEGIN
FOR I IN 1 TO 3 DO
OUT_TEXT := :OUT_TEXT || :I || ' ';
END FOR;
RETURN 'inside: ' || :OUT_TEXT || '/ after the loop I is ' || :I;
END;
$$;| status |
|---|
| Function FORUNDECLARED_T147 successfully created. |
CALL FORUNDECLARED_T147();| FORUNDECLARED_T147 |
|---|
| inside: 1 2 3 / after the loop I is 99 |
Inside the loop we saw the loop's values. After the loop the declared variable is exactly what it was before. The loop variable is a different thing entirely and the declared one was never touched.
What happens when the bounds are the wrong way round?
A reasonable guess is either an error or one pass. Let's find out.
CREATE OR REPLACE PROCEDURE FORREVERSED_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
HOW_MANY NUMBER DEFAULT 0;
BEGIN
FOR I IN 4 TO 1 DO
HOW_MANY := :HOW_MANY + 1;
END FOR;
RETURN 'the body ran ' || :HOW_MANY || ' times';
END;
$$;| status |
|---|
| Function FORREVERSED_T147 successfully created. |
CALL FORREVERSED_T147();| FORREVERSED_T147 |
|---|
| the body ran 0 times |
Neither. The body ran no times at all, and nothing complained.
So if you want to count down there has to be a word for it, and there is.
CREATE OR REPLACE PROCEDURE FORDOWNWARD_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
OUT_TEXT VARCHAR DEFAULT '';
BEGIN
FOR I IN REVERSE 1 TO 4 DO
OUT_TEXT := :OUT_TEXT || :I || ' ';
END FOR;
RETURN 'visited: ' || :OUT_TEXT;
END;
$$;| status |
|---|
| Function FORDOWNWARD_T147 successfully created. |
CALL FORDOWNWARD_T147();| FORDOWNWARD_T147 |
|---|
| visited: 4 3 2 1 |
REVERSE in front of the range, and the same range walked backwards.
Now WHILE and REPEAT, with the same impossible condition
These two look similar and differ in exactly one way. The cleanest way to see it is to give both of them a condition that can never let the body run, and count the passes.
First a WHILE whose condition is false before it starts.
CREATE OR REPLACE PROCEDURE WHILEFALSE_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
HOW_MANY NUMBER DEFAULT 0;
GUARD NUMBER DEFAULT 0;
BEGIN
WHILE (1 = 2) DO
HOW_MANY := :HOW_MANY + 1;
GUARD := :GUARD + 1;
IF (:GUARD > 10) THEN
BREAK;
END IF;
END WHILE;
RETURN 'the while body ran ' || :HOW_MANY || ' times';
END;
$$;| status |
|---|
| Function WHILEFALSE_T147 successfully created. |
CALL WHILEFALSE_T147();| WHILEFALSE_T147 |
|---|
| the while body ran 0 times |
It tested first and never entered the body.
Now a REPEAT with an UNTIL that is true immediately.
CREATE OR REPLACE PROCEDURE REPEATFALSE_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
HOW_MANY NUMBER DEFAULT 0;
GUARD NUMBER DEFAULT 0;
BEGIN
REPEAT
HOW_MANY := :HOW_MANY + 1;
GUARD := :GUARD + 1;
IF (:GUARD > 10) THEN
BREAK;
END IF;
UNTIL (1 = 1)
END REPEAT;
RETURN 'the repeat body ran ' || :HOW_MANY || ' times';
END;
$$;| status |
|---|
| Function REPEATFALSE_T147 successfully created. |
CALL REPEATFALSE_T147();| REPEATFALSE_T147 |
|---|
| the repeat body ran 1 times |
The body ran once. REPEAT tests at the bottom, so the body always runs at least once whatever the condition says.
That is the whole difference between them, and it is worth having seen it rather than read it.
And how do you stop a loop the condition will not stop?
With BREAK. Here is a WHILE whose condition is always true, with a guard inside it that stops the loop after a fixed number of passes.
CREATE OR REPLACE PROCEDURE GUARDSTOPS_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
HOW_MANY NUMBER DEFAULT 0;
BEGIN
WHILE (1 = 1) DO
HOW_MANY := :HOW_MANY + 1;
IF (:HOW_MANY >= 5) THEN
BREAK;
END IF;
END WHILE;
RETURN 'stopped after ' || :HOW_MANY || ' passes, by the guard and not the condition';
END;
$$;| status |
|---|
| Function GUARDSTOPS_T147 successfully created. |
CALL GUARDSTOPS_T147();| GUARDSTOPS_T147 |
|---|
| stopped after 5 passes, by the guard and not the condition |
The guard ended it, and the message says how many passes it took to get there. This is the shape every loop in this post is written with, because a runaway loop in a worksheet is a miserable way to spend an afternoon.
The other one is CONTINUE, which abandons the rest of the current pass and goes straight to the next. Here it skips the even numbers.
CREATE OR REPLACE PROCEDURE CONTINUING_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
OUT_TEXT VARCHAR DEFAULT '';
BEGIN
FOR I IN 1 TO 6 DO
IF (MOD(:I, 2) = 0) THEN
CONTINUE;
END IF;
OUT_TEXT := :OUT_TEXT || :I || ' ';
END FOR;
RETURN 'kept: ' || :OUT_TEXT;
END;
$$;| status |
|---|
| Function CONTINUING_T147 successfully created. |
CALL CONTINUING_T147();| CONTINUING_T147 |
|---|
| kept: 1 3 5 |
Only the odd values were kept. The assignment after the CONTINUE never ran on the even passes.
Now a loop that writes a row on every pass
Everything so far has only built up a string. Let's put an INSERT inside a FOR loop and write to the table we made at the start.
CREATE OR REPLACE PROCEDURE LOOPDML_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
FOR I IN 1 TO 4 DO
INSERT INTO TRACE_T147 (STEP, NOTE) VALUES (:I, 'pass ' || :I);
END FOR;
RETURN 'done';
END;
$$;| status |
|---|
| Function LOOPDML_T147 successfully created. |
CALL LOOPDML_T147();| LOOPDML_T147 |
|---|
| done |
So let's look at the table.
SELECT STEP, NOTE FROM TRACE_T147 ORDER BY STEP;| STEP | NOTE |
|---|---|
| 1 | pass 1 |
| 2 | pass 2 |
| 3 | pass 3 |
| 4 | pass 4 |
One row per pass, with the loop variable written into each one. Nothing surprising yet, and that is deliberate, because the next section is the same shape with one line added.
And now the one that matters: what survives a failure?
Here is the same loop over a different range, with one extra IF in it. On the pass where the loop variable reaches 12 it raises an error on purpose, after that pass has already inserted its row.
CREATE OR REPLACE PROCEDURE LOOPFAILS_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
FOR I IN 10 TO 13 DO
INSERT INTO TRACE_T147 (STEP, NOTE) VALUES (:I, 'pass ' || :I);
IF (:I = 12) THEN
RAISE STATEMENT_ERROR;
END IF;
END FOR;
RETURN 'never reached';
END;
$$;| status |
|---|
| Function LOOPFAILS_T147 successfully created. |
That range is four passes. The failure happens on the third of them, so it is not a tidy halfway point, and the RETURN at the bottom is never reached. Let's call it.
CALL LOOPFAILS_T147();-20000 (P0001): Uncaught exception of type 'STATEMENT_ERROR' on line 6 at position 12
An uncaught exception, so the CALL failed. Now the question that actually matters. What is in the table?
SELECT STEP, NOTE FROM TRACE_T147 WHERE STEP >= 10 ORDER BY STEP;| STEP | NOTE |
|---|---|
| 10 | pass 10 |
| 11 | pass 11 |
| 12 | pass 12 |
Three rows, one for each pass that got as far as its INSERT. The row written by the pass that then raised is there too.
The inserts that ran before the failure were not rolled back.
There is no implicit transaction around a loop, and there is none around a procedure either. A procedure that fails half finished leaves the table half changed.
If you want all or nothing you write BEGIN TRANSACTION yourself, and roll back from an exception handler. That was the last post.
One last thing: every block is closed by its own name
A few refusals to finish with, and they all make the same point.
First, labelled loops. Other databases let you name a loop and then break out of that particular one by name, which is handy when they are nested.
CREATE OR REPLACE PROCEDURE LABELLED_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
HOW_MANY NUMBER DEFAULT 0;
BEGIN
OUTER_LOOP: FOR I IN 1 TO 3 DO
FOR J IN 1 TO 3 DO
HOW_MANY := :HOW_MANY + 1;
IF (:HOW_MANY >= 4) THEN
BREAK OUTER_LOOP;
END IF;
END FOR;
END FOR;
RETURN 'the inner body ran ' || :HOW_MANY || ' times before breaking out';
END;
$$;001003 (42000): SQL compilation error: syntax error line 5 at position 14 unexpected ':'. syntax error line 5 at position 22 unexpected 'IN'.
001003, and the error points at the colon after the label. That form is not accepted on this version, so the procedure never existed.
CALL LABELLED_T147();002139 (02000): SQL compilation error: Unknown function LABELLED_T147.
Now the terminators. Here is a WHILE loop closed with END IF.
CREATE OR REPLACE PROCEDURE WRONGEND_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
N NUMBER DEFAULT 0;
BEGIN
WHILE (:N < 2) DO
N := :N + 1;
END IF;
RETURN 'never reached';
END;
$$;001003 (42000): SQL compilation error: syntax error line 7 at position 8 unexpected 'IF'.
A syntax error at the IF. It wanted END WHILE and nothing else will do.
And a FOR loop closed with END LOOP, which is the generic spelling other databases use.
CREATE OR REPLACE PROCEDURE ENDLOOP_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
N NUMBER DEFAULT 0;
BEGIN
FOR I IN 1 TO 2 DO
N := :N + 1;
END LOOP;
RETURN 'never reached';
END;
$$;001003 (42000): SQL compilation error: syntax error line 7 at position 8 unexpected 'LOOP'.
A syntax error at the LOOP. There is no generic END LOOP here. END IF, END CASE, END FOR, END WHILE, END REPEAT, and each one only closes its own kind of block.
And one I am leaving open
A BREAK with no loop around it at all.
CREATE OR REPLACE PROCEDURE LOOSEBREAK_T147()
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
BREAK;
RETURN 'never reached';
END;
$$;| status |
|---|
| Function LOOSEBREAK_T147 successfully created. |
Created successfully. Snowflake accepted the definition without a word, which I did not expect.
I did not capture a call of it, so I am not going to tell you what it does when it runs. If you try it, you will know before I do.
Key points
IFtakes its condition in brackets, and the brackets are not optional. Leaving them off is001003.- The middle branch is
ELSEIF, one word. ELSIFis a syntax error. That is the spelling people coming from other databases reach for.ELSE IF, two words, is a nestedIFinside theELSEbranch, and it needs a secondEND IF.CASEworks as a statement as well as an expression, and a statement ends withEND CASE.- An unmatched
CASEwith noELSEcarries on quietly. It is not an error. - The searched form of the statement works too, and both forms of
CASEcan appear in one body. - A
FORloop declares its own loop variable, and a declared variable of the same name is a separate thing that survives the loop untouched. - Reversed bounds run the body no times at all, with no error. To count down the word is
REVERSE. WHILEtests first, so an impossible condition means no passes.REPEATtests last, so the body always runs once.BREAKends a loop whose condition will never end it.CONTINUEabandons the rest of one pass.- A loop that fails part way through keeps every row it had already written.
- There is no implicit transaction around a loop or around a procedure. If you want all or nothing, write
BEGIN TRANSACTIONyourself. - Labelled loops with
BREAKby name are refused on this version. - Every block is closed by its own name, and there is no generic
END LOOP.
In the next post we walk a query row by row: cursors and RESULTSETs. Both of them will walk a query exactly once, and each one has its own way of starting over.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. Every loop in it is bounded by a guard, which is on screen in the bodies above. The agreed title for this episode says the loop failed half way; the capture shows the range was four passes and the failure came on the third, so the text says part way through instead. Every count in the text is read off one of the grids on this page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake Scripting branching and looping documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.