The IIF(X, Y, Z) function behaves like if-else logic. In the IIF(X, Y, Z) function:
X is the expression to be evaluated and checked for the true condition.Y is returned if the evaluation of X is true.Z is returned if the evaluation of X is false.iif(condition, true_expression_or_value, false_expression_or_value)
Logically, this is equivalent to:
CASE
WHEN CONDITION
THEN
TRUE_VALUE
ELSE
FALSE_VALUE
END
True valueSELECT IIF( 100 > 30, 'True' , 'False' ) RESULT;
Output
RESULT
---------
True
In the above code, we have checked if 100 > 30. This is a true condition, so the true value True is returned.
False valueSELECT IIF( 100 < 30, 'True' , 'False' ) RESULT;
Output
RESULT
---------
False
In the above code, we have checked if 100 < 30. This is a false condition, so the false value False is returned.
Let’s say we have a table with some data about students:
| Name | Age |
|---|---|
| Ram | 18 |
| Raj | 15 |
| Abu | 10 |
| Andrew | 8 |
We will write a query to show if the user is eligible to vote in the output:
SELECTname,age,IIF(age<18, 'Not Eligible', 'Eligible') as can_voteFROM students;
In the above code, we have created a select query to fetch name and age, and added an IIF function to check if the age is less than Not Eligible; otherwise, the IIF function will return Eligible. The returned values are available in the can_vote column.
| Name | Age | can_vote |
|---|---|---|
| Ram | 18 | Eligible |
| Raj | 15 | Not Eligible |
| Abu | 10 | Not Eligible |
| Andrew | 8 | Not Eligible |
You can test the SQLite online here.