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;
Copy

Where:

condition

An expression that evaluates to a BOOLEAN.

statement

A statement can be any of the following:

  • A single SQL statement (including CALL).

  • A control-flow statement (for example, a looping or branching statement).

  • A nested block.

Usage notes

  • The keyword THEN is required.

  • ELSEIF is one word (no spaces).

  • END IF is two words.

  • After each THEN or ELSE clause, the body allows the BEGIN and END keywords, but does not require them, even if the body contains more than one statement.

  • If the condition is 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;
$$
;
Copy

Here is the command to call the stored procedure, along with the output:

CALL example_if(3);
Copy
+-------------------+
| EXAMPLE_IF        |
|-------------------|
| Unexpected input. |
+-------------------+

For more examples that use the IF statement, see: