CASE Expressions
A CASE expression is used like an if-then-else construct to conditionally return a value. There are two forms of syntax for CASE expression, the simple form and the searched form. The simple form is used to test a single operand for equality against multiple expressions. The searched form of a CASE expression is more flexible and allows for testing multiple conditions.
For more information on using CASE expressions in the select list of SELECT statement, see The Select List.
Simple CASE Expression
The simple CASE expression implies equality (=) is used for comparisons. One <common_operand> is tested against multiple values. It is frequently used to transform one set of values to another longer form.
CASE <common_operand> WHEN <expression> THEN <result> [WHEN <expression> THEN <result> . . .] [ELSE <result>] ENDFor example:
SELECT lastname, CASE gender WHEN ‘M’ THEN ‘Male’ WHEN ‘m’ THEN ‘Male’ WHEN ‘0’ THEN ‘Male’ WHEN ‘F’ THEN ‘Female’ WHEN ‘f’ THEN ‘Female’ WHEN ‘1’ THEN ‘Female’ ELSE ‘Unknown’ END FROM employeesEquality expressions cannot be used to test for NULL so you cannot use a simple CASE expression to test for NULL. You must use a searched CASE expression with IS NULL or IS NOT NULL when testing for NULL.
Searched CASE Expression
The searched CASE expression is good to use when you want to work with a greater range of tests. Any boolean expression qualifies as a WHEN <expression>.
CASE WHEN <condition> THEN <result> [WHEN <condition> THEN <result> . . .] [ELSE <result>] ENDThe result of the first true boolean expression is returned. For example, the following SELECT statement uses a searched CASE expression to prevent division by zero:
SELECT ProductID, Name, ProductNumber, Cost, ListPrice, CASE WHEN ListPrice = 0 THEN NULL ELSE Cost / ListPrice END AS CostOfGoodSold FROM ProductThe searched CASE expression can also be used to test a result column for NULL whereas a simple CASE expression cannot. The following simple CASE expression is invalid:
SELECT CASE middle_name WHEN NULL THEN ‘<NULL>’ ELSE middle_name ENDIn SQL you cannot use equality to test if a column is NULL (empty). Instead you must use 'IS NULL' as follows:
SELECT CASE WHEN middle_name IS NULL THEN ‘<NULL>’ ELSE middle_name END