G-4240: Always use a CASE instead of a NVL2 command if parameter 2 or 3 of NVL2 is either a function call or a SELECT statement.

Critical

Efficiency, Reliability

Reason

The NVL2 function always evaluates all parameters before deciding which one to use. This can be harmful, if parameter 2 or 3 is either a function call or a select statement, as they will be executed regardless of whether parameter 1 contains a NULL value or not.

Example (bad)

SELECT NVL2(dummy, my_package.expensive_nn(value_in => dummy), 
                   my_package.expensive_null(value_in => dummy))
  FROM dual;

Example (good)

SELECT CASE
          WHEN dummy IS NULL THEN 
             my_package.expensive_null(value_in => dummy)
          ELSE 
             my_package.expensive_nn(value_in => dummy)
       END
FROM dual;