SQL Server IF vs IIF(): What’s the Difference?

Students learning a new programming language will often start their first lesson with an IF statement, where their statement will return a value only if the expression is true.

They might then progress to an IF... ELSE statement, where they can determine another value to return if the expression is false. So therefore, return one value if the expression is true, and another value if it’s false.

SQL Server certainly includes the IF... ELSE statement in its T-SQL toolbox.

SQL Server also includes the IIF() function, which does a similar thing, but with a more concise syntax.

But there are some subtle differences.

Continue reading

How IIF() Works in SQL Server

In SQL Server, the IIF() function (not to be confused with the IF statement) is a conditional function that returns the second or third argument based on the evaluation of the first argument.

It’s a shorthand way for writing a CASE expression. It’s logically equivalent to CASE WHEN X THEN Y ELSE Z END assuming IIF(X, Y, Z).

IIF() is an abbreviation for Immediate IF.

Continue reading