In this article, we’ll go through IIF and CASE and then compare IIF vs CASE.
IIF is one of the logical Transact-SQL function which returns one among the two values, based on the boolean expression. On the other hand, CASE is a language expression which evaluates a list of conditions and returns one among multiple values, based on the boolean expression.
So, IIF function can be easily replaced with CASE expression. Simultaneously a CASE expression which could return ane among two values can also be interchanged with IIF function.
Now, let us see the major differences of these two options:
IIF vs CASE
# | IIF | CASE |
---|---|---|
1 | IIF was introduced in SQL Server 2012 | CASE was introduced in SQL server 2008 |
2 | IIF is a function | CASE is an expression |
3 | Used to return one of the two values. | Used to return one from two or more values. |
4 | Syntax: IIF ( boolean-expression, value-for-true, value-for-false ) | Syntax: CASE input-expression WHEN when-expression THEN result-expression [ …n ] [ ELSE else-result-expression ] END |
5 | Example: DECLARE @i int = 100, @j int = 200; SELECT IIF ( @i > @j, ‘GREATER’, ‘SMALLER’ ) AS Result; | Example: DECLARE @i int = 200 SELECT CASE @i WHEN 100 THEN ‘ONE HUNDRED’ WHEN 200 THEN ‘TWO HUNDRED’ WHEN 300 THEN ‘THREE HUNDRED’ ELSE ‘Something Else’ END; |
Related Articles
- Comparison between SELECT and SET.
- Differences between VARCHAR(MAX) and VARCHAR(N).
- Usage and performance comparison between Union and Union All.
I like IIF() because it’s faster and cleaner than CASE. However, having said that, I use IIF() only if there is only one condition to evaluate. CASE was built for multiple condition evaluations and does an excellent job with them, whereas multiple condition evaluations with IIF() leads to nested IIF() statements which can get real ugly real fast. Anyone who has created complicated IF() formulas in Excel knows what I’m talking about.
Excellent Comparison, I will suggest to use SQL case over IIF as it is much easier to use, but if there are lots of CASE it can make code difficult to read.
If anyone needs more SQL switch case example, you can check this article
https: //qawithexperts.com /article /sql /understanding-sql-server-switch-case-with-example /147
Thanks