Reference Guide > TDV Support for SQL Operators > Condition Operators > CASE
 
CASE
The CASE operator is used to evaluate several conditions and return a single value for the first matched condition. The CASE expression is similar to an IF-THEN-ELSE or a SWITCH statement used in many programming languages. However, in SQL, CASE is an expression, not a statement.
CASE has two formats:
Simple CASE
Searched CASE
Simple CASE
A simple CASE compares an expression to a set of simple expressions.
Syntax
CASE <comparison-value>
WHEN <conditional-expression 1> THEN <scalar-expression 1>
WHEN <conditional-expression 2> THEN <scalar-expression 2>
WHEN <conditional-expression 3> THEN <scalar-expression 3>
[ELSE <default-scalar-expression>]
END
Remarks
Using CASE, you can express an alternate value to an underlying value. For example, if the underlying value is a code (such as 1, 2, 3), you can display it as a humanly readable string value (Small, Medium, Large), without affecting the underlying value.
If none of the test conditions is true, CASE returns the result contained in the optional ELSE case, if one is specified.
If no match is found and ELSE is not specified, ELSE NULL is assumed by default.
Example
SELECT ProductID, Status, UnitPrice,
CASE Status
WHEN 'open' THEN UnitPrice * 1.10
WHEN 'closed' THEN UnitPrice * 1
ELSE UnitPrice
END
AS "New Price"
FROM /shared/examples/ds_orders/orderdetails
Searched CASE
A searched CASE compares an expression to a set of logical expressions.
Syntax
CASE
WHEN <conditional_expression_1> THEN <scalar_expression_1>
WHEN <conditional_expression_2> THEN <scalar_expression_2>
WHEN <conditional_expression_3> THEN <scalar_expression_3>
[ELSE <default_scalar_expression>]
END
Examples
SELECT ProductID, UnitPrice
CASE
WHEN UnitPrice <=100 THEN 'Between $1 and $100.00'
WHEN UnitPrice <=200 THEN 'Between $100.01 and $200.00'
ELSE 'Over $200.00'
END
AS "Price Range"
FROM /shared/examples/ds_orders/orderdetails
 
SELECT ProductID, UnitPrice
CASE
WHEN UnitPrice > 400 THEN 'Above 400.00'
WHEN UnitPrice >=300 THEN 'Between 300 and 400.00'
END
AS "Price Range"
FROM /shared/examples/ds_orders/orderdetails