A more readable alternative to SQL’s CASE expression
Abstract
Introducing SQL’s function decode
as a more readable and maybe more performant alternative to the case-expression, usable when the conditions all have a certain structure.
For a certain kind of case-when-then-expression, you can use the SQL function decode
as an alternative that I find more readable and that I prefer whenever I can.
Granted, the case
expression is much more flexible than decode
and can thus be used under many more circumstances, but it’s exactly the limits of decode
for which I immediately valued it once I first heard of decode
. The restrictions of decode
mean that whenever I see decode
being used, I know exactly what awaits me reading the coming code and, more importantly, what cannot await me. Whenever I see decode
, I can be certain that it’s that particular use case.
At my workplace, I’m the code owner of much of our SQL code and I thus review a lot of SQL code that was written by other people. After I learned about SQL’s decode
function, I taught it to my colleagues and am always grateful when they use it.