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
| Parameter | Required | Type | Description |
|---|---|---|---|
testCondition | Yes | BOOLEAN expression | The condition to evaluate. |
valueTrue | Yes | Any | The value to return when testCondition is TRUE. |
valueFalseOrNull | Yes | Any | The 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.
该文章对您有帮助吗?