Sub topic 2
Replacing NULL with NVL
This chapter assumes you can write basic SELECT statements with WHERE and column aliases, know the Oracle data types NUMBER and VARCHAR2, and can use the DUAL table for quick tests. NULL means a missing or unknown value, and it does not equal anything, including itself.
NVL takes two arguments. If the first is NULL, NVL returns the second. Otherwise it returns the first.
Basic use of NVL
SELECT employee_id,
salary,
NVL(commission_pct, 0) AS commission
FROM employees;Employees without a commission rate show 0 instead of NULL.
Branching on NULL with NVL2
NVL2 takes three arguments. It returns the second argument when the first is not NULL, and the third when the first is NULL.
SELECT employee_id,
NVL2(commission_pct, 'Salary + commission', 'Salary only') AS pay_type
FROM employees;Returning the first non-NULL value with COALESCE
COALESCE accepts any number of arguments and returns the first one that is not NULL. It returns NULL only when every argument is NULL.
SELECT contact_id,
COALESCE(mobile_phone, work_phone, home_phone, 'no phone on file') AS best_phone
FROM contacts;Matching data types of replacement values
The replacement value must be compatible with the first argument's data type. Oracle tries to convert the replacement to that type. Text such as 'none' cannot convert to a number, so this query fails:
-- Raises ORA-01722: invalid number
SELECT NVL(commission_pct, 'none') FROM employees;Convert the numeric column to text first:
SELECT NVL(TO_CHAR(commission_pct), 'none') AS commission
FROM employees;Exercise
Exercise
What does NVL2(NULL, 'yes', 'no') return, and why?
Show answer
It returns 'no'. The first argument is NULL, so NVL2 returns its third argument.