Chapter 6 SQL Language Elements
233
IF statement is different from IF expression
Do not confuse the syntax of the IF expression with that of the IF
statement.
$ For information on the IF statement, see "IF statement" on page 545.
CASE expressions
The CASE expression provides conditional SQL expressions. Case
expressions can be used anywhere an expression can be used.
The syntax of the CASE expression is as follows:
CASE expression
WHEN expression
THEN expression,...
[ ELSE expression ]
END
If the expression following the CASE statement is equal to the expression
following the WHEN statement, then the expression following the THEN
statement is returned. Otherwise the expression following the ELSE
statement is returned, if it exists.
For example, the following code uses a case expression as the second clause
in a SELECT statement.
SELECT id,
( CASE name
WHEN ’Tee Shirt’ then ’Shirt’
WHEN ’Sweatshirt’ then ’Shirt’
WHEN ’Baseball Cap’ then ’Hat’
ELSE ’Unknown’
END ) as Type
FROM "DBA".Product
An alternative syntax is as follows:
CASE
WHEN search-condition
THEN expression,...
[ ELSE expression ]
END
If the search-condition following the WHEN statement is satisfied, the
expression following the THEN statement is returned. Otherwise the
expression following the ELSE statement is returned, if it exists.