IF (Snowflake Scripting)¶
An IF statement provides a way to execute a set of statements if a condition is met.
For more information on branching constructs, see Working with conditional logic.
Note
This Snowflake Scripting construct is valid only within a Snowflake Scripting block.
Syntax¶
IF ( <condition> ) THEN
<statement>;
[ <statement>; ... ]
[
ELSEIF ( <condition> ) THEN
<statement>;
[ <statement>; ... ]
]
[
ELSE
<statement>;
[ <statement>; ... ]
]
END IF;
Where:
Usage notes¶
The keyword
THENis required.ELSEIFis one word (no spaces).END IFis two words.After each
THENorELSEclause, the body allows theBEGINandENDkeywords, but does not require them, even if the body contains more than onestatement.If the
conditionis NULL, then it is treated as FALSE.
Examples¶
Here is an example of a Snowflake Scripting IF statement inside a stored procedure:
CREATE OR REPLACE PROCEDURE example_if(flag INTEGER)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
IF (FLAG = 1) THEN
RETURN 'one';
ELSEIF (FLAG = 2) THEN
RETURN 'two';
ELSE
RETURN 'Unexpected input.';
END IF;
END;
$$
;
Here is the command to call the stored procedure, along with the output:
CALL example_if(3);
+-------------------+
| EXAMPLE_IF |
|-------------------|
| Unexpected input. |
+-------------------+
For more examples that use the IF statement, see:
Working with conditional logic - Return different values based on IF conditions in a simple anonymous block.
Examples for common use cases of Snowflake Scripting - Execute SQL statements based on IF conditions in loops.
BREAK, LOOP, and Working with loops - Execute BREAK statements to terminate a loop based on IF conditions.
EXCEPTION - Raise exceptions based on IF conditions.