DECLARE VARIABLE

Description

The DECLARE VARIABLE statement is used to create a temporary variable in Spark. Temporary variables are scoped at a session level.

You can reference variables by their name everywhere constant expressions are allowed. Unless you qualify a variable with session or system.session, a variable is only resolved after Spark fails to resolve a name to a column or column alias.

Temporary variables cannot be referenced in persisted objects such as persisted view, column default expressions, and generated column expressions.

Syntax

DECLARE [ OR REPLACE ] [ VARIABLE ]
    variable_name [ data_type ] [ { DEFAULT | = } default_expr ]

Parameters

Examples

-- The dense form of declaring a variable with default
DECLARE five = 5;

-- STRING variable initialialized to `NULL`
DECLARE some_var STRING;