IIF (TSQL Function)

Returns the true_value if boolean_expression is true. Else, returns false_value.

Syntax

IIF ( boolean_expression , true_value , false_value )

Arguments

boolean_expression
is an expression of type bool.
true_value
is an expression of any type.
false_value
is an expression of any type.

Return Types

Returns the type of true_value or false_value, which has the highest type precedence.

Examples

DECLARE @a int = 20, @b int = 10;
PRINT IIF(@a > @b, 'Hello', 'Goodbye');

The result is:

Hello

Example with different argument types:

PRINT IIF(20 > 10, '2000', 123)  -- the string '2000' can be converted to int
PRINT IIF(20 > 10, 'Hello', 123) -- the string 'Hello' cannot be converted to int

The result type is int, because it has higher precedence than varchar:

2000
<Conversion error. VARCHAR "Hello" cannot be cast into INT, invalid string.>
RSQL, a simple alternative to Microsoft SQL Server