IIF() Function in SQL Server

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

Overview

The IIF() function evaluates the first parameter, if the evaluated value is true, it will return the second parameter, and it will return the third parameter.

This article explains the SQL Server IIF() function in detail and demonstrates multiple examples for easy understanding.

What is IIF() Function in SQL Server?

In the SQL server, the IIF() function works like a ternary operator that evaluates an expression and returns one of the two values based on whether the expression is true or false.

Note:
IIF stands for Immediate IF. The term Immediate IF implies that the expression evaluation and decision-making happen immediately, as the function is executed.

Let's look at the syntax, parameters, and return type of the function to understand how it exactly works.

Syntax of IIF() Function in SQL Server

This function has three parameters which we will discuss in the next section.

Parameters of IIF() Function in SQL Server

  • boolean_expression:
    The expression to be evaluated. The result must be a boolean value otherwise the function will raise an error.
  • value_if_true:
    Resulting value if the boolean_expression is truthy.
  • value_if_false:
    Resulting value if the boolean_expression is falsy.

The second and the third parameters must be of compatible data types, as the function needs to return a consistent data type regardless of whether the boolean_expression is true or false.

Return Type of IIF() Function in SQL Server

The return value of the IIF() function is determined by the data type of the two possible result values provided as second and third arguments to the function.

Similarity Between IIF Function and CASE Statement in SQL Server

The IIF() function can also be expressed in the form of a CASE statement. Let's see how.

If the IIF() function statement looks like this:

The equivalent CASE statement to the above code will be:

Both the above codes have the same meaning, it's just that using the IIF() function is more concise.

Using the CASE statement will make more sense if the logic gets more complicated.

SQL Server IIF() Function Examples

1. Simple Example of SQL Server IIF() Function

In this example, we will return True if the boolean expression is true, if not, we will return False.

SQL Server Code:

Output:

Result
True

The IIF() function is returning True as 1<21 \lt 2.

2. Returning Number Using IIF() Function in SQL Server

In this example, we will return 5 if the boolean expression is true, otherwise, we will return 10.

SQL Server Code:

Output:

Result
5

The IIF() function is returning 5 as a result because 5<105 \lt 10.

3. Checking if Two Strings are the Same Using the IIF() Function in SQL Server

In this example, we will check if two strings are the same, if yes, we will return True, otherwise, we will return False.

SQL Server Code:

Output:

String1String2IsEqual
Save WaterSave WaterYes

The IIF() function is returning Yes as the str1 and str2 strings are equal.

4. Using SQL Server IIF() Function with Table Column

Before proceeding to use the IIF() function with a table, we must create a table first.

Let's create a Students table with the following schema:

Students Schema:

Column NameData TypeDescription
roll_noINT (Primary Key)Roll number of the student
student_nameVARCHAR(50)Name of the student
maths_marksINTMarks obtained in Mathematics
physics_marksINTMarks obtained in Physics
chemistry_marksINTMarks obtained in Chemistry

Now we will create the Students table and fill it with some values.

SQL Server Code:

The resultant table will look like this:

roll_nostudent_namemaths_marksphysics_markschemistry_marks
1Hagemaru233419
2Luke1009589
3Momo395045
4Gandalf891890
5Snow77901

Let's play with this table using the IIF() function in SQL Server!

We will use the IIF() function to find out who failed which exam, the passing threshold will be 40 marks.

SQL Server Code:

Output:

roll_nostudent_namemaths_resultphysics_resultchemistry_result
1HagemaruFailFailFail
2LukePassPassPass
3MomoFailPassPass
4GandalfPassFailPass
5SnowPassPassFail

As we can see in the output our code has worked perfectly fine. The IIF() returned FAIL wherever the marks were less than 40 and returned Pass if the marks were more than or equal to 40.

5. Using Aggregate Function with IIF() Function in SQL Server

To save the hassle, let's use the Students table which we created in the previous example (example 4).

We will find the total number of passed students in each subject using the IIF() function and an aggregate function.

SQL Server Code:

Output:

passed_in_mathspassed_in_physicspassed_in_chemistrytotal_students
3335

In the above example, the IIF() function returns 1 if the marks are passing marks, otherwise, it returns 0. The SUM() is then used to count the number of 1's to find the number of students passed in each subject.

6. Using Nested IIF() Functions in SQL Server

Now we will demonstrate nested IIF() functions using the same Students table that we created in the 4th example.

In this example, we will use nested IIF() functions to categorize the average marks of each student into four categories: Excellent, Good, Average, and Poor.

SQL Server Code:

Output:

roll_nostudent_namegrade
1HagemaruPoor
2LukeExcellent
3MomoPoor
4GandalfAverage
5SnowAverage

In this example, we are using a subquery to calculate the average marks for each student. After that, we use nested IIF() functions to categorize the average marks into their corresponding categories.

Conclusion

  1. The IIF() function in SQL Server is similar to a ternary operator in programming languages. It evaluates a given boolean expression, and if the expression is true, it returns one specified value; otherwise, it returns a different specified value.
  2. The return type of the IIF() function is the same as the data type of its parameters.
  3. The data type of the IIF() function's second and third parameters must be consistent, otherwise the results can be unexpected.
  4. The IIF() function is used in simple logic whereas the CASE statement will be given more preference for complex logic building.
  5. We can nest IIF() functions inside IIF() functions multiple times as per our needs.