IF

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 Branching Constructs.

Syntax

IF ( <condition> ) THEN
    <statement>;
    [ <statement>; ... ]
[
ELSEIF ( <condition> ) THEN
    <statement>;
    [ <statement>; ... ]
]
[
ELSE
    <statement>;
    [ <statement>; ... ]
]
END IF;

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 (e.g. 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;
$$
;

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

CALL example_if(3);
+-------------------+
| EXAMPLE_IF        |
|-------------------|
| Unexpected input. |
+-------------------+
Back to top