Sub topic 3
How the arguments are evaluated
This chapter assumes you know basic SELECT and WHERE clauses, column aliases, the DUAL table, and the aggregate functions COUNT, AVG, and SUM. It also assumes you know that NULL means a missing value.
How the arguments are evaluated
COALESCE returns its first argument that is not NULL and stops there. Later arguments are not evaluated. NVL and NVL2 do not work this way in the same sense, so an error in a later argument can still surface.
SELECT COALESCE(1, 1/0) AS first_wins FROM dual;The query returns 1. The division by zero is never reached.
NVL, NVL2, or COALESCE: choosing the right one
| Function | Arguments | Use it when |
|---|---|---|
| NVL(a, b) | 2 | You want one default for NULL |
| NVL2(a, b, c) | 3 | You want one value when a is NULL and another when it is not |
| COALESCE(a, b, ...) | 2 or more | You want the first non-NULL value from a list |
NULL in aggregates
COUNT(column), AVG, and SUM skip NULL values. COUNT(*) counts every row.
SELECT COUNT(*) AS all_rows,
COUNT(commission_pct) AS earners,
AVG(commission_pct) AS avg_among_earners,
AVG(NVL(commission_pct, 0)) AS avg_across_everyone
FROM employees;Replacing NULL with 0 before AVG changes the result, because the average now includes every row.
The NOT IN trap and other filter pitfalls
SELECT 'row returned' AS msg FROM dual WHERE 1 NOT IN (2, NULL);This query returns no rows. NOT IN is true only when every comparison is true, and 1 = NULL is unknown, so the condition never becomes true.
Comparisons such as commission_pct <> 0 also skip rows where the column is NULL.
Related functions: NULLIF and DECODE
NULLIF(a, b) returns NULL when a equals b, and otherwise returns a. DECODE is an Oracle function that treats two NULLs as equal.
SELECT NULLIF(0, 0) AS nullif_result,
DECODE(NULL, NULL, 'match', 'no match') AS decode_result
FROM dual;Exercise
Why does SELECT 1 FROM dual WHERE 1 NOT IN (2, NULL); return no rows?
Show answer
NOT IN is true only when every comparison is true. The comparison 1 = NULL is unknown, so the whole condition is never true.