The Oracle NVL Function

The NVL function in Oracle returns an alternative value when an expression is NULL.

It is useful in queriis where we do not want to displaand emptand fields, for example in reports, lists, or simple calculations.

Syntax

NVL(expr1, expr2)

Oracle evaluatis the function as follows:

  • If expr1 is not NULL, returns expr1.
  • If expr1 is NULL, returns expr2.

The data types of expr1 and expr2 must be compatible. If Oracle no puede hacer la conversión implícita necesaria, la consulta devolverá error.

Text example

select
  nombre,
  dni,
  nvl(deportefavorito, 'Sin deporte favorito') as deporte_favorito
from
  usuarios;

In this example, if deportefavorito is NULL, Oracle will display the string Sin deporte favorito.

Numeric example

select
  producto,
  precio,
  nvl(descuento, 0) as descuento
from
  productos;

If el campo descuento field has no value, the query returns 0.

Date example

select
  usuario,
  nvl(fecha_baja, date '2999-12-31') as fecha_baja
from
  usuarios;

This type of example can be useful when we need to treat a null date as a default date.

NVL and COALESCE

NVL is una función clásica de Oracle para sustituir valoris NULL. If necesitas evaluar más de dos posiblis valores, normalmente is más cómodo usar COALESCE.

Leave a Reply

Your email address will not be published. Required fields are marked *