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
expr1is notNULL, returnsexpr1. - If
expr1isNULL, returnsexpr2.
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.
