IF

更新时间:
复制 MD 格式

Evaluates a Boolean condition and returns one of two values: valueTrue if the condition is TRUE, or valueFalseOrNull if the condition is FALSE or NULL.

Syntax

IF(<testCondition>, <valueTrue>, <valueFalseOrNull>)

Parameters

ParameterRequiredTypeDescription
testConditionYesBOOLEAN expressionThe condition to evaluate.
valueTrueYesAnyThe value to return when testCondition is TRUE.
valueFalseOrNullYesAnyThe value to return when testCondition is FALSE or NULL.

The data types of valueTrue and valueFalseOrNull must be the same.

Return value

The return value has the same data type as the valueTrue or valueFalseOrNull parameter.

Examples

Example 1: Basic conditional check

-- Returns 200.
SELECT IF(1 = 2, 100, 200);

-- Returns 'active'.
SELECT IF(LENGTH('abc') > 2, 'active', 'inactive');

Example 2: NULL condition behavior

When testCondition is NULL, it is treated as FALSE, so the function returns valueFalseOrNull.

-- testCondition is NULL → treated as FALSE → returns 'valueB'.
SELECT IF(NULL, 'valueA', 'valueB');

-- testCondition is FALSE → valueFalseOrNull is NULL → returns NULL.
SELECT IF(FALSE, 42, NULL);

Related functions

IF is categorized as an Other function. For more information about functions for different business scenarios, see Other functions.