It is now two and a half year since my former partner wrote a tip about the CASE expression in SQL. I often end up helping people with their SQL statements and when I use the CASE expression, they haven't seen it before. So it is time to reprint it, now in english.
The CASE expression was added to the DB2 SQL syntax in version 5. The CASE expression comes in two flavours, the "simple WHEN" and the "searched WHEN". Let's start with the syntax of the "simple WHEN":
And here is an example of its use:
If the ELSE is omitted and column PGM_LANG contains other values than C2, P1 or AS, the CASE expression returns the NULL value. Before version 5 it was common to use a UNION to produce the same result set as in the example, but it had a cost of three extra scans of the PGM_TABLE table. Now let's look at the syntax of a "searched WHEN":
And (big surprise) now an example:
In this example I translate the status of all the programs to a meaningful value based on a date interval. This is an ideal task for the "searched WHEN" expression and could not be solved with the "simple WHEN" expression.
I have shown examples where the CASE expression is used only in the SELECT list, but it can be used anywhere in the SQL-statement, where you can use an expression. When used in the WHERE-clause you must be careful, because it can or will influence your access path and maybe lead to unwanted response times.