In SQL, the IIF function helps you choose between two values based on a condition. It allows you to perform a conditional evaluation.
It's similar to the CASE statement, with a simpler and shorter syntax for basic situations.
IIF(condition, value_if_true, value_if_false)
• condition is the expression that is evaluated.
• value_if_true is returned if the condition evaluates to true.
• value_if_false is returned if the condition evaluates to false.
1. Let's assume we have a table named "[Student]".
2. Let's assume you want to pass students depending on their scores. If their score is more than 21, they pass; otherwise, they fail.
3. Run below SQL statement :
SELECT Student_Name, Score, IIF(Score > 21, 'Pass', 'Fail') AS Result FROM Student;
4. In the above statement, if the score is greater than 21 then the student is 'Pass' otherwise, 'Fail'.
The IIF function in SQL is like a smart helper that helps you make decisions in your database. It checks a condition for you, and then gives you one result if the condition is true, and another if it's false. It's handy when you need to choose between different values based on some condition.
Using this function in a select statement won't modify the [Student] table directly, but it will only be reflected in the select statement's output.
The IIF function in SQL returns one of two values depending on whether the specified condition evaluates to true or false.
The difference between IF and IIF in SQL is that IF is used for flow control within procedural code (like stored procedures), while IIF is a scalar function used to return a value based on a condition.
The difference between IIF and CASE in T-SQL is that CASE is more flexible and allows for multiple conditions and branches, while IIF is simpler and only handles a single condition.
IIF does exist in SQL, but its availability depends on the specific database management system (DBMS) being used. It's commonly supported in systems like Microsoft SQL Server and Microsoft Access.