Why put NVL around WHEN in SQL?

67 Views Asked by At

I was reading a query and came upon the following code:

nvl(case when month>start then null else 0 end, 1)

and it seemed to me there was no reason for the nvl.

Why not do this:

case when month>start then 1 else 0 end

?

1

There are 1 best solutions below

2
Knut Boehnert On

This is an escape clause to get the correct result when [month] has the value NULL.

Comparing NULL > start will yield 0 instead of 1. Using the NVL function will correct the NULL value to 1 as intended.

In case that [month] can never be NULL (column check?) then this code is redundant.