You are on page 1of 1

106 Chapter 3: Selecting

The CASE expression comes in two forms:


<case_expression> ::= <basic_case_expression>
| <searched_case_expression>

<basic_case_expression> ::= CASE <basic_expression>


WHEN <expression> THEN <expression>
{ WHEN <expression> THEN <expression> }
[ ELSE <expression> ]
END
The first format evaluates the CASE <basic_expression> and compares it in
turn to the value of each WHEN <expression>. This comparison implicitly uses
the equals = operator. The result of this comparison may be TRUE, FALSE,
or UNKNOWN. If a TRUE result is encountered, thats as far as the process
gets; the corresponding THEN <expression> is evaluated and returned as the
result of the CASE. If all the comparisons result in FALSE or UNKNOWN,
then the ELSE <expression> is evaluated and returned; if there is no ELSE
<expression>, then NULL is returned.
Following is an example where a basic CASE expression is used to convert
the string values in sales_order.region into a number suitable for sorting. The
result of the CASE expression is given an alias name, sort_order, and that alias
name is referenced by both the WHERE clause and the ORDER BY clause.
SELECT CASE region
WHEN 'Western' THEN 1
WHEN 'Central' THEN 2
WHEN 'Eastern' THEN 3
ELSE 0
END AS sort_order,
region,
COUNT(*) AS orders
FROM sales_order
WHERE sort_order > 0
GROUP BY region
ORDER BY sort_order;
Heres the result; not only has an explicit sort order been defined, but all the
orders outside those three regions have been excluded:
sort_order region orders
========== ======= ======
1 Western 61
2 Central 224
3 Eastern 244
The second form of the CASE expression is more flexible; you are not limited
to the implicit equals = operator, nor are you limited to a single CASE com-
parison value on the left side of all the WHEN comparisons.
<searched_case_expression> ::= CASE
WHEN <boolean_expression> THEN <expression>
{ WHEN <boolean_expression> THEN <expression> }
[ ELSE <expression> ]
END
Each WHEN <boolean_expression> is evaluated, in turn, to result in a TRUE,
FALSE, or UNKNOWN result. As soon as a TRUE result is encountered, the
search is over; the corresponding THEN <expression> is evaluated and returned
as the result of the CASE. If all the results are FALSE or UNKNOWN, then the

You might also like