Introduction
In this post, we’ll explore the IIF SQL functionality. IIF (If and only if) function, and we’ll use the AdventureWorks database for our testing purposes. Let’s get started.
What’s IIF Function?
- Introduced in SQL Server 2012
- This function returns one of two values depending on the boolean expression [also known as condition] that evaluates true or false.
- IIF is composed of the logical statement, the boolean expression known as the condition, followed by the “true” and the “false” expressions.
- This function can be compared to CASE expressions and a shorthand way of writing a CASE expression.
IIF Syntax
-- Syntax
IIF(boolean_expressions, true, false)
-- OR
IIF(condition, true, false)
- Boolean expression or condition – this is required, and it is because of the value that needs to be tested.
- True - this is optional, but the value is returned if the condition is true.
- False - this is optional, but the value is returned if the condition is false.
Examples
1. Compare Numbers
-- Let's declare and initialize two numbers
DECLARE @NUM1 INT = 20;
DECLARE @NUM2 INT = 25
--OUTPUT: 25 is greater than 20
SELECT IIF( (@NUM2 > @NUM1), FORMATMESSAGE('%i is greater than %i', @NUM2, @NUM1),
FORMATMESSAGE('%i is greater than %i', @NUM1, @NUM2))
AS [ComparingNumbers];
--OUTPUT: TRUE
SELECT IIF(@NUM2 > @NUM1, 'TRUE', 'FALSE') AS [ComparingNumbers];
SET @NUM1 = 120;
SET @NUM2 = 25;
--OUTPUT: 120 is greater than 25
SELECT IIF((@NUM1 > @NUM2), FORMATMESSAGE('%i is greater than %i', @NUM1, @NUM2),
FORMATMESSAGE('%i is greater than %i', @NUM2, @NUM1))
AS [ComparingNumbers];
--OUTPUT: TRUE
SELECT IIF(@NUM2 > @NUM1, 'FALSE', 'TRUE') AS [ComparingNumbers];
As you can see from the example we have shown how we can easily compare numbers using the IIF function.
Output

2. Compare numbers within a table column
This section will try to explore some examples using the AdventureWorks database. Checking the Person Person table of the AdventureWorks database, you’ll see a NameStyle column. This column uses bit as its datatype. When it is 0, FirstName and LastName are stored in Western-style (first name, last name). Otherwise, when it is 1, it is stored in an Eastern-style (Lastname, first name) order.
Let’s try to use the IIF function here.
USE [AdventureWorks2019]
/** Let’s try to format the person’s names using either western-style or eastern-style by using IIF.*/
SELECT IIF(NameStyle = 0,
CONCAT(FirstName, ', ' , LastName),
CONCAT(LastName, ', ', FirstName))
FROM
[Person].[Person]
Output

3. Compare strings within a table column
In this example, we’ll try to get the Employee’s marital status by using the IIF function and joining the two tables [HumanResources].[Employee] and [Person].[Person] inside the AdventureWorks database. The column MaritalStatus uses the nchar(1) datatype, and M stands for married, while S stands for single.





Join the conversation! Your thoughts help the community grow.