The goal of this article is providing explanations about using
CASE expression and its alternatives which introduced in SQL Server 2012. This article is completely compatible with SQL Server 2012 and 2014.
Table of Contents
Introduction
SQL Server 2012 introduces these two new functions which simplify CASE expression:
- Conditional function ( IIF)
- Selection function ( CHOOSE )
We also have been working with COALESCE, an old simplified CASE expression statement as a NULL-related statement since early versions. Although ISNULL is a function, which logically simplifies a CASE expression, but it never translates to a CASE expression behind the scene (by execution plan). By the way, we will also cover ISNULL in this article, as it is an alternative to COALESCE. The goal of this article is providing in depth tutorial about these statements:
- ISNULL
- COALESCE
- IIF
- CHOOSE
I prefer using the term “statement” because although they do similar job, but they are not in same category by their purpose. For example, ISNULL is a function while COALESCE is an expression.
As we will see later, the main purpose of introducing these statements is improving code readability and achieving cleaner code. Using these statements may result to poor performancein some situations. Therefore, we also will discuss alternative solutions.
This article targets all levels of readers: from newbies to advanced. So, if you are familiar with these statements, you may prefer skipping Definition section.
Definition
ISNULL
ISNULL(expr_1, expr_2)If expr_1 is null, then ISNULL function returns expr_2, otherwise returns expr_1. Following example shows its functionality.
DECLARE@expr_1 NVARCHAR(10) , @expr_2 NVARCHAR(10) ;SET@expr_1 = NULL;SET@expr_2 = N'Saeid';SELECT@expr_1 ASexpr_1, @expr_2AS
expr_2, ISNULL(@expr_1, @expr_2)AS
[ISNULLResult]When the data types of two arguments are different, if they areimplicitly convertible, SQL Server converts one to the other, otherwise returns an error. Executing follow code results an error as illustrated in output figure.
DECLARE@Val_1 INT, @Val_2 NVARCHAR(10) ;SET@Val_1 = NULL;SET@Val_2 = 'Saeid';SELECT@Val_1 AS[Value 1], @Val_2AS
[Value 2], ISNULL(@Val_1, @Val_2)AS
[ISNULLResult]Changing value of variable @Val_2 to ‘500’, we do not encounter any error. Because this value is convertible to numeric data type INT. Following code shows this:
DECLARE@Val_1 INT, @Val_2 NVARCHAR(10) ; SET@Val_1 = NULL;SET@Val_2 = '500';SELECT@Val_1 AS[Value 1], @Val_2AS
[Value 2], ISNULL(@Val_1, @Val_2)AS
[ISNULLResult]Implicit conversion may lead to data truncation. This will happen if the length of expr_1 data typeis shorter than length of expr_2 data type. So it is better to convert explicitly if needed. In the next example first output column suffers from value truncation while second will not.
DECLARE@Val_1 NVARCHAR(2) , @Val_2 NVARCHAR(10) ;SET@Val_1 = NULL;SET@Val_2 = 'Saeid';SELECTISNULL(@Val_1, @Val_2)AS
[ISNULLResult], ISNULL(CONVERT(NVARCHAR(10),
@Val_1), @Val_2) AS
[ISNULLResultwith
explicit convert]
Determine output data type
There are few rules to determine output column's data type generated via ISNULL. The next code illustrates these rules:
IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL DROPTABLE
dbo.TestISNULL ;DECLARE@Val_1 NVARCHAR(200) , @Val_2 DATETIME ;SET@Val_1 = NULL;SET@Val_2 = GETDATE() ;SELECTISNULL('Saeid', @Val_2)AS
Col1, ISNULL(@Val_1, @Val_2)AS
Col2, ISNULL(NULL, @Val_2)AS
Col3, ISNULL(NULL,NULL) AS
Col4 INTOdbo.TestISNULLWHERE1 = 0 ;GOSELECTCOLUMN_NAME , DATA_TYPE , CHARACTER_MAXIMUM_LENGTHFROMINFORMATION_SCHEMA.COLUMNS WHERETABLE_SCHEMA = N'dbo' ANDTABLE_NAME = N'TestISNULL';
Determine output NULL-ability
Follow code illustrates the rules to determine output column data type generated via ISNULL:
IF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL DROPTABLE
dbo.TestISNULL ;DECLARE@Val_1 NVARCHAR(200) , @Val_2 DATETIME ;SET@Val_1 = NULL;SET@Val_2 = GETDATE() ;SELECTISNULL('Saeid', @Val_2)AS
Col1, ISNULL(@Val_1, @Val_2)AS
Col2 INTOdbo.TestISNULLWHERE1 = 0 ;GOSELECTCOLUMN_NAME , IS_NULLABLEFROMINFORMATION_SCHEMA.COLUMNS WHERETABLE_SCHEMA = N'dbo' ANDTABLE_NAME = N'TestISNULL';
COALESCE
COALESCE(expr_1, expr_2, ..., expr_n) ,(for n >=2)COALESCE returns the first NOT NULL expression in the expression list. It needs at least two expressions.
Dissimilar from ISNULL function, COALESCE is not a function, rather it’s an expression. COALESCE always translates to CASE expression. For example,
COALESCE (expr_1, expr_2)
is equivalent to:
CASE
WHEN (expr_1 IS NOT NULL) THEN (expr_1)
ELSE (expr_2)
END
Therefore the database engine handles it like handling a CASE expression. So this is inside our simplified CASE expression list.
Following code is one of many samples that could illustrate different execution plans for COALESCE and ISNULL:
USE AdventureWorks2012 ;GOSELECT* FROMSales.SalesOrderDetailWHEREISNULL(ProductID, SpecialOfferID) = 3 ;SELECT* FROMSales.SalesOrderDetailWHEREcoalesce(ProductID, SpecialOfferID) = 3 ;By using COALESCE, we do not have the limitations that discussed about ISNULL function, neither about output column data type nor output column NULL-ability. Even there is no more suffering from value truncation. The next example is the new revision of the ISNULL section examples, but replacing with COALESCE:
-- value truncationDECLARE@Val_1 NVARCHAR(2) , @Val_2 NVARCHAR(10) ;SET@Val_1 = NULL;SET@Val_2 = 'Saeid';SELECTISNULL(@Val_1, @Val_2)AS
[ISNULLResult], ISNULL(CONVERT(NVARCHAR(10),
@Val_1), @Val_2) AS
[ISNULLResultwith
explicit convert], COALESCE(@Val_1, @Val_2)AS
[COALESCEResult]GO------------------------------------------------------------ output data typeIF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL DROPTABLE
dbo.TestISNULL ;DECLARE@Val_1 NVARCHAR(200) , @Val_2 DATETIME ;SET@Val_1 = NULL;SET@Val_2 = GETDATE() ;SELECTCOALESCE('Saeid', @Val_2)AS
Col1, COALESCE(@Val_1, @Val_2)AS
Col2, COALESCE(NULL, @Val_2)AS
Col3INTOdbo.TestISNULLWHERE1 = 0 ;GOSELECTCOLUMN_NAME , DATA_TYPE , CHARACTER_MAXIMUM_LENGTHFROMINFORMATION_SCHEMA.COLUMNS WHERETABLE_SCHEMA = N'dbo' ANDTABLE_NAME = N'TestISNULL';GO------------------------------------------------------------ NULL-abilityIF OBJECT_ID('dbo.TestISNULL','U') ISNOTNULL DROPTABLE
dbo.TestISNULL ;DECLARE@Val_1 NVARCHAR(200) , @Val_2 DATETIME ;SET@Val_1 = NULL;SET@Val_2 = GETDATE() ;SELECTCOALESCE('Saeid', @Val_2)AS
Col1, COALESCE(@Val_1, @Val_2)AS
Col2 INTOdbo.TestISNULLWHERE1 = 0 ;GOSELECTCOLUMN_NAME , IS_NULLABLEFROMINFORMATION_SCHEMA.COLUMNS WHERETABLE_SCHEMA = N'dbo' ANDTABLE_NAME = N'TestISNULL';GOIIF
IIF( condition , x, y)IIF is a logical function which was introduced in SQL Server 2012. It is like conditional operator in C-Sharp language. When condition is true, x evaluated, else y evaluated. Following example illustrates this function usage.
DECLARE@x NVARCHAR(10) , @y NVARCHAR(10) ;SET@x = N'True'
;SET@y = N'False'
;SELECTIIF( 1 = 0, @x, @y) AS[IIF Result]Like COALESCE expression, IIF function always translates to CASE expression. For instance,
IIF ( condition, true_value, false_value )
is equivalent to:
Case
when (condition is true) then (true_value)
Else (false_value)
End
This example shows that this translation.
USE AdventureWorks2012 ;GOSELECT*FROMSales.SalesOrderDetailWHEREIIF ( OrderQty >= SpecialOfferID , OrderQty, SpecialOfferID ) = 1
CHOOSE
CHOOSE(index, val_1, val_2, ..., val_n) ,(for n >=1)CHOOSE is a selection function which was introduced in SQL Server 2012. It’s like switch operator in C-Sharp language. If index (must be convertible to data type INT) is NULL or its value is not found, the output will be NULL. This function needs at least two arguments, one for index and other for value. Following code illustrates this function usage.
DECLARE@indexINT
;SET@index= 2 ;SELECTCHOOSE(@index,'Black', 'White', 'Green')Like COALESCE expression and IIF function, CHOOSE also always translates to CASE expression. For example,
CHOOSE ( index, val_1, val_2 )
is equivalent to:
Case
when (index = 1) then val_1
when (index = 2) then val_2
Else NULL
End
This simple code shows that this translation.
USE AdventureWorks2012 ;GOSELECT*FROMSales.SalesOrderDetailWHERECHOOSE(OrderQty, 'Black','White', 'Green') = 'White'
Performance
Although the main purpose of simplified CASE expression statements is increasing readability and having cleaner codes, but one important question is how these statements impact on the database performance. Is there any performance
difference between CASE expression and these statements? By the way, to achieve best performance it’s usually better to find alternative solutions and avoid using CASE and these statements.
Dynamic filtering
This is common to write reports which accept input parameters. To achieve better performance it’s a good practice to write their code within stored procedures, because procedures store the way of their executing as an execution
plan and reuse it again. By the way, there are some popular solutions to write this type of procedures.
IS NULL and OR
This is the most common solution. Let me start with an example and rewrite it with comparable solutions:
USE AdventureWorks2012;GOIF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL DROPPROC Sales.SalesOrderDetailSearch ;GOCREATEPROC Sales.SalesOrderDetailSearch @ModifiedDateAS
DATETIME = NULL
, @ShipDateAS
DATETIME = NULL
, @StoreIDAS
INT= NULLAS SELECT b.ShipDate , c.StoreID , a.UnitPriceDiscount , b.RevisionNumber , b.DueDate , b.ShipDate , b.PurchaseOrderNumber , b.TaxAmt , c.PersonID , c.AccountNumber , c.StoreID FROM Sales.SalesOrderDetail a RIGHTOUTERJOIN
Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID LEFTOUTERJOIN
Sales.Customer c ON
b.CustomerID = c.CustomerID WHERE (a.ModifiedDate = @ModifiedDate OR@ModifiedDate ISNULL) AND(b.ShipDate = @ShipDate OR@ShipDate ISNULL) AND(c.StoreID = @StoreID OR@StoreID ISNULL)GO------------------------------------------------- now execute it with sample valuesEXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @StoreID = 602The main problem here, as illustrated in above figure, is using same execution plan for all the three situations. It’s obvious that the third one suffers from an inefficient execution plan.
CASE
We can change the combination of IS NULL and OR and translate it using CASE. Now we rewrite above code like this one:
USE AdventureWorks2012;GOIF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL DROPPROC Sales.SalesOrderDetailSearch ;GOCREATEPROC Sales.SalesOrderDetailSearch @ModifiedDateAS
DATETIME = NULL
, @ShipDateAS
DATETIME = NULL
, @StoreIDAS
INT= NULLAS SELECT b.ShipDate , c.StoreID , a.UnitPriceDiscount , b.RevisionNumber , b.DueDate , b.ShipDate , b.PurchaseOrderNumber , b.TaxAmt , c.PersonID , c.AccountNumber , c.StoreID FROM Sales.SalesOrderDetail a RIGHTOUTERJOIN
Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID LEFTOUTERJOIN
Sales.Customer c ON
b.CustomerID = c.CustomerID WHERE a.ModifiedDate = CASEWHEN
@ModifiedDate IS
NOTNULL
THEN@ModifiedDate ELSEa.ModifiedDate END ANDb.ShipDate = CASEWHEN
@ShipDate IS
NOTNULL
THEN@ShipDate ELSEb.ShipDate END ANDc.StoreID = CASEWHEN
@StoreID IS
NOTNULL
THEN@StoreID ELSEc.StoreID ENDGO------------------------------------------------- now execute it with sample valuesEXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @StoreID = 602Using CASE shows improvements to IS NULL and OR, but with more CPU cost for the first one. Also the Reads and Actual Rows decreased in first two executions. So it’s better but still we continue our experiment.
COALESCE
We also can change CASE and translate it to COALESCE. Now we rewrite above code like this:
USE AdventureWorks2012;GOIF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL DROPPROC Sales.SalesOrderDetailSearch ;GOCREATEPROC Sales.SalesOrderDetailSearch @ModifiedDateAS
DATETIME = NULL
, @ShipDateAS
DATETIME = NULL
, @StoreIDAS
INT= NULLAS SELECT b.ShipDate , c.StoreID , a.UnitPriceDiscount , b.RevisionNumber , b.DueDate , b.ShipDate , b.PurchaseOrderNumber , b.TaxAmt , c.PersonID , c.AccountNumber , c.StoreID FROM Sales.SalesOrderDetail a RIGHTOUTERJOIN
Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID LEFTOUTERJOIN
Sales.Customer c ON
b.CustomerID = c.CustomerID WHERE a.ModifiedDate = COALESCE(@ModifiedDate, a.ModifiedDate) ANDb.ShipDate = COALESCE(@ShipDate, b.ShipDate) ANDc.StoreID = COALESCE(@StoreID, c.StoreID)GO------------------------------------------------- now execute it with sample valuesEXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @StoreID = 602It’s obvious that because COALESCE translates to CASE internally, so there is no difference between them.
ISNULL
Now we rewrite above code and use ISNULL instead of COALESCE:
USE AdventureWorks2012;GOIF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL DROPPROC Sales.SalesOrderDetailSearch ;GOCREATEPROC Sales.SalesOrderDetailSearch @ModifiedDateAS
DATETIME = NULL
, @ShipDateAS
DATETIME = NULL
, @StoreIDAS
INT= NULLAS SELECT b.ShipDate , c.StoreID , a.UnitPriceDiscount , b.RevisionNumber , b.DueDate , b.ShipDate , b.PurchaseOrderNumber , b.TaxAmt , c.PersonID , c.AccountNumber , c.StoreID FROM Sales.SalesOrderDetail a RIGHTOUTERJOIN
Sales.SalesOrderHeader b ONa.SalesOrderID = b.SalesOrderID LEFTOUTERJOIN
Sales.Customer c ON
b.CustomerID = c.CustomerID WHERE a.ModifiedDate = ISNULL(@ModifiedDate, a.ModifiedDate) ANDb.ShipDate = ISNULL(@ShipDate, b.ShipDate) ANDc.StoreID = ISNULL(@StoreID, c.StoreID)GO------------------------------------------------- now execute it with sample valuesEXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @StoreID = 602There is no change in Duration, but with more estimated rows.
Dynamic SQL
Using above four solutions we could not achieve good performance, because we need different efficient execution plan for each combination of input parameters. So it’s time to use an alternative solution to overcome this problem.
USE AdventureWorks2012;GOIF OBJECT_ID('Sales.SalesOrderDetailSearch','P') ISNOTNULL DROPPROC Sales.SalesOrderDetailSearch ;GOCREATEPROC Sales.SalesOrderDetailSearch @ModifiedDateAS
DATETIME = NULL
, @ShipDateAS
DATETIME = NULL
, @StoreIDAS
INT= NULLASDECLARE@sql NVARCHAR(MAX), @parameters NVARCHAR(4000) ;SET@sql = ' SELECT b.ShipDate , c.StoreID , a.UnitPriceDiscount , b.RevisionNumber , b.DueDate , b.ShipDate , b.PurchaseOrderNumber , b.TaxAmt , c.PersonID , c.AccountNumber , c.StoreID FROM Sales.SalesOrderDetail a RIGHT OUTER JOIN Sales.SalesOrderHeader b ON a.SalesOrderID = b.SalesOrderID LEFT OUTER JOIN Sales.Customer c ON b.CustomerID = c.CustomerID WHERE 1 = 1 ' IF @ModifiedDateIS
NOTNULL SET@sql = @sql + ' AND a.ModifiedDate = @xModifiedDate ' IF @ShipDateIS
NOTNULL SET@sql = @sql + ' AND OrderQty = @xShipDate ' IF @StoreIDIS
NOTNULL SET@sql = @sql + ' AND ProductID = @xStoreID 'SET@parameters = '@xModifiedDate AS DATETIME , @xShipDate AS DATETIME , @xStoreID AS INT';EXECsp_executesql @sql, @parameters, @ModifiedDate, @ShipDate, @StoreID ;GO------------------------------------------------- now execute it with sample valuesEXECSales.SalesOrderDetailSearch @ModifiedDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @ShipDate = '2008-04-30 00:00:00.000'EXECSales.SalesOrderDetailSearch @StoreID = 602There is no doubt that this solution is the best one! Here is the comparison chart. (lower is better)
You can find more information about last solution inErland Sommarskog website.
Concatenate values in one column
This is another common problem that fits our discussion. In this example we just cover COALESCE and ISNULL solutions and at last we will see an alternative solution which performs better than using the CASE solutions.
COALESCE
Next code concatenates the values of column “ProductID” and delimites each with comma separator.
USE AdventureWorks2012GODECLARE@sql NVARCHAR(MAX);SELECT@sql = COALESCE(@sql +', ', '') +CONVERT(NVARCHAR(100), ProductID)FROMSales.SalesOrderDetailWHERESalesOrderID < 53000This code executed in 13 seconds in our test system.
ISNULL
Now we rewrite above code and use ISNULL instead of COALESCE:
USE AdventureWorks2012GODECLARE@sql NVARCHAR(MAX);SELECT@sql = ISNULL(@sql +', ', '') +CONVERT(NVARCHAR(100), ProductID)FROMSales.SalesOrderDetailWHERESalesOrderID < 53000The duration decreased to 3 seconds.
XML
It’s time to use alternative solution to overcome this problem.
USE AdventureWorks2012GODECLARE@sql NVARCHAR(MAX);SELECT @sql = ( SELECTSTUFF(( SELECT ','+ CONVERT(NVARCHAR(100), ProductID)AS
[text()] FROM Sales.SalesOrderDetail WHERE SalesOrderID < 53000 FOR XML PATH('') ), 1, 1,'') ) ;The duration decreased to 21 milliseconds. Here is the comparison chart. (lower is better)
Note that XML runs at lowest duration.
There is no doubt that this solution is the best one. But because using XML, this solution has some limitations related to XML reserved characters like "<" or ">".
Branch program execution based on switch between possible values
This is so common to use CHOOSE function to write cleaner codes. But is it the best solution to achieve optimal performance? In this section we will discuss about this question.
CHOOSE
Let’s start with an example that uses CHOOSE as its solution.
USE AdventureWorks2012 ;GOSELECT* FROMSales.SalesOrderDetailWHERECHOOSE(OrderQty, 'J','I', 'H','G', 'F','E', 'D','C', 'B','A') IN( 'J','Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL)GOThis code executed in 352 milliseconds in our test system.
UDF function
Now we rewrite above code and use a Table Valued Function to produce CHOOSE list:
USE AdventureWorks2012 ;GOCREATEFUNCTION
ufnLookup ()RETURNSTABLEASRETURN SELECT1 ASIndexer, 'J'
ASval UNIONALL SELECT2, 'I' UNIONALL SELECT3, 'H' UNIONALL SELECT4, 'G' UNIONALL SELECT5, 'F' UNIONALL SELECT6, 'E' UNIONALL SELECT7, 'D' UNIONALL SELECT8, 'C' UNIONALL SELECT9, 'B' UNIONALL SELECT10, 'A'GOSELECT* FROMSales.SalesOrderDetail aJOINdbo.ufnLookup() b ONa.OrderQty = b.IndexerWHEREb.val IN
( 'J', 'Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL) ;The duration decreased to 195 milliseconds.
Permanent Lookup Table
It’s time to use alternative solution to overcome this problem.
USE AdventureWorks2012 ;GOCREATETABLE
LookupTable( idINT
PRIMARYKEY, valCHAR(1) ) ;GOINSERTdbo.LookupTable ( id, val ) SELECT1 ASIndexer, 'J'
ASval UNIONALL SELECT2, 'I' UNIONALL SELECT3, 'H' UNIONALL SELECT4, 'G' UNIONALL SELECT5, 'F' UNIONALL SELECT6, 'E' UNIONALL SELECT7, 'D' UNIONALL SELECT8, 'C' UNIONALL SELECT9, 'B' UNIONALL SELECT10, 'A'
;GOSELECT* FROMSales.SalesOrderDetail aJOINdbo.LookupTable b ONa.OrderQty = b.IdWHEREb.val IN
( 'J', 'Q', 'H','G', 'X','E', 'D','Y', 'B','A', NULL)The duration decreased to 173 milliseconds. Next figure shows the comparison chart between these solutions. (lower is better)
This solution is the best one. By increasing the number of values in parameter list of CHOOSE function, the performance decreases. So by using permanent look-up table that benefits from physical index we can achieve the best performance.
More Readability
The most important goal to use these simplified CASE statements is achieve cleaner code. Many times we encounter this issue that code is so large that the SELECT list becomes more than hundred lines of code. Therefore there is a significant reason to use these statements. I was faced a simple problem just few years ago. In first sight it seems that solution should be very simple. But after writing the code using CASE, I found that I am in trouble. The problem was so simple. Assume that a department store has two discount plan, one based on purchases amount, and other based on the distance from customer’s home to store. But the rule was that just one plan that is greater is applicable. Next code shows two solutions, first by using CASE and second uses IIF.
IF OBJECT_ID('tempdb..#temp','U') ISNOTNULL DROPTABLE
#temp
;CREATETABLE
#temp
( CustomerId INT, Bill MONEY, DistanceINT
) ;INSERT#temp ( CustomerId, Bill, Distance )VALUES( 1, 30.00, 3 ), ( 2, 10.00, 8 ), ( 3, 5.00, 14 ), ( 4, 20.00, 21 ), ( 5, 25.00, 23 ), ( 6, 5.00, 27 ) ;SELECT*FROM#temp-- solution using CASESELECT CASE WHEN CASEWHEN
Bill < 10.00 THEN
10 ELSE
20 END> CASE
WHENDistance < 10 THEN7 ELSE13 END THENCASE
WHENBill < 10.00 THEN10 ELSE20 END ELSECASE
WHENDistance < 10 THEN7 ELSE13 END ENDAS
DiscountFROM#temp--solution using IIFSELECT IIF( IIF( Bill < 10.00 , 10 ,20 ) > IIF( Distance < 10 , 7 , 13 ) ,IIF( Bill < 10.00 , 10 ,20 ) , IIF( Distance < 10 , 7 , 13 ) )AS
DiscountFROM#tempAs illustrate in above code, IIF solution is more readable.
Conclusion
Using simplified CASE expression statements results to have cleaner code and speed up development time, but they show poor performance in some situations. So if we are in performance tuning phase of software development, it’s better to think about alternative solutions.






















