Sub topic 8
Working with NULL
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query in an Oracle session and know what rows, columns, and the common data types are. It covers what NULL means, how it behaves in comparisons and expressions, and how to handle it in the output. The examples use the HR sample schema, mainly the employees table. In that table, commission_pct is NULL for employees who do not earn commission, and manager_id is NULL for the top of the hierarchy.
What NULL is
NULL marks a value that is missing or unknown. It is not zero, and it is not an empty string, and it is not a space. A salary of 0 is a known value. A NULL salary means no value is recorded.
Oracle treats NULL differently from other databases in one respect. Oracle treats a zero-length string as NULL when it is stored in a VARCHAR2 column or evaluated as a VARCHAR2 value. '' and NULL therefore behave the same way in most Oracle string expressions. Many other databases keep them separate.
SELECT CASE WHEN '' IS NULL THEN 'empty string is NULL'
ELSE 'empty string is not NULL'
END AS result
FROM dual;This query returns empty string is NULL in Oracle.
Three-valued logic
A condition in SQL has three possible results: TRUE, FALSE, or UNKNOWN. A comparison that involves NULL gives UNKNOWN. This is true even when you compare NULL with NULL.
| Expression | Result |
|---|---|
| `NULL = NULL` | UNKNOWN |
| `NULL <> NULL` | UNKNOWN |
| `5 > NULL` | UNKNOWN |
| `NULL IS NULL` | TRUE |
| `5 IS NOT NULL` | TRUE |
A WHERE clause keeps a row only when its condition is TRUE. Rows where the condition is FALSE or UNKNOWN are dropped. That rule explains most of the surprises people meet with NULL.
SELECT COUNT(*) AS wrong_count
FROM employees
WHERE commission_pct = NULL;This query returns 0. The comparison is UNKNOWN for every row, so no row passes the filter. Oracle does not raise an error, which makes the mistake easy to miss.
Testing for NULL with IS NULL and IS NOT NULL
Use IS NULL and IS NOT NULL to test for NULL.
SELECT employee_id, last_name, commission_pct
FROM employees
WHERE commission_pct IS NULL
ORDER BY employee_id;SELECT employee_id, last_name, commission_pct
FROM employees
WHERE commission_pct IS NOT NULL
ORDER BY commission_pct DESC;The two queries split the table into two groups with no overlap. Every row has either a NULL or a non-NULL commission_pct.
Comparisons silently exclude NULL rows
A filter such as commission_pct <> 0.2 does not return the rows where commission_pct is NULL. Those rows give UNKNOWN, so the filter drops them. If you want them, say so in the condition.
SELECT first_name, last_name, commission_pct
FROM employees
WHERE commission_pct <> 0.2
OR commission_pct IS NULL;The query from the topic plan combines the two ideas. It returns employees with no commission, plus employees whose commission is above 0.2. It also replaces NULL with 0 in the output column.
SELECT first_name, last_name, NVL(commission_pct, 0) AS commission
FROM employees
WHERE commission_pct IS NULL OR commission_pct > 0.2;NVL changes only the value shown in the result. The WHERE clause still tests the original column, so IS NULL is still needed there.
Logical operators and NULL
AND, OR, and NOT follow three-valued logic. The truth tables below show the cases that include UNKNOWN.
| A | B | A AND B | A OR B |
|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
NOT UNKNOWN is UNKNOWN. This is why negating a condition does not give you the complement set of rows. The next two queries do not add up to the whole table.
SELECT COUNT(*) FROM employees WHERE commission_pct > 0.2;
SELECT COUNT(*) FROM employees WHERE NOT (commission_pct > 0.2);The rows with NULL commission_pct appear in neither result.
NULL in arithmetic and string expressions
Any arithmetic expression that has a NULL operand returns NULL.
SELECT 10 + NULL AS sum_result,
10 * NULL AS product_result
FROM dual;Both columns show NULL. A common consequence is a total pay calculation that goes missing for employees without commission:
SELECT last_name,
salary + salary * commission_pct AS total_pay
FROM employees
WHERE department_id = 80;Where commission_pct is NULL, total_pay is NULL as well. The fix is to substitute a value for the NULL before it enters the calculation.
SELECT last_name,
salary + salary * NVL(commission_pct, 0) AS total_pay
FROM employees
WHERE department_id = 80;The || concatenation operator is an exception. Oracle treats a NULL operand as an empty string, so concatenation does not return NULL just because one side is NULL.
SELECT 'Ora' || NULL || 'cle' AS joined_text FROM dual;This returns Oracle.
Functions that handle NULL
Oracle has several single-row functions for replacing or producing NULL. Each fits a slightly different case.
| Function | Behavior |
|---|---|
| `NVL(a, b)` | Returns `b` if `a` is NULL, otherwise `a` |
| `NVL2(a, b, c)` | Returns `b` if `a` is not NULL, otherwise `c` |
| `COALESCE(a, b, c, ...)` | Returns the first non-NULL argument |
| `NULLIF(a, b)` | Returns NULL if `a` equals `b`, otherwise `a` |
SELECT last_name,
commission_pct,
NVL(commission_pct, 0) AS nvl_value,
NVL2(commission_pct, 'Has commission', 'No commission') AS commission_status,
COALESCE(commission_pct, 0) AS coalesce_value
FROM employees
WHERE department_id IN (80, 90)
ORDER BY last_name;NVL and COALESCE give the same answer here. They differ in two ways that matter.
COALESCEaccepts any number of arguments.NVLaccepts exactly two.NVLalways evaluates both arguments.COALESCEstops at the first non-NULL argument, a behavior called short-circuit evaluation. If the second argument is an expensive function call,COALESCEcan avoid it.
NVL also converts the second argument to the data type of the first. COALESCE requires compatible types and can raise an error if they are not. Always pass arguments of the same type to either function.
NULLIF works in the opposite direction. It turns a specific value into NULL. A common use is to avoid division by zero:
SELECT NULLIF(10, 10) AS same_values,
NULLIF(10, 20) AS different_values,
100 / NULLIF(0, 0) AS safe_divide
FROM dual;The first column is NULL, the second is 10, and the third is NULL because dividing by NULL does not raise an error.
NULL in sorting
ORDER BY has to place NULL somewhere. In Oracle, NULL is treated as larger than any other value. So NULL appears last in ascending order and first in descending order.
SELECT last_name, commission_pct
FROM employees
WHERE department_id = 80
ORDER BY commission_pct DESC;You can override the default with NULLS FIRST or NULLS LAST.
SELECT last_name, commission_pct
FROM employees
WHERE department_id = 80
ORDER BY commission_pct DESC NULLS LAST;NULL and DISTINCT
For DISTINCT, two NULLs count as the same value. A query that selects DISTINCT department_id from employees returns one NULL row if any employee has no department. In the HR schema, one employee (Kimberely Grant) has no department.
SELECT DISTINCT department_id
FROM employees
ORDER BY department_id;Here DISTINCT groups NULLs together even though NULL = NULL is UNKNOWN in a WHERE clause. GROUP BY does the same thing.
NULL in aggregate functions
Aggregate functions skip NULL values, with one exception. COUNT(*) counts rows. COUNT(column) counts only rows where the column is not NULL.
SELECT COUNT(*) AS all_rows,
COUNT(commission_pct) AS with_commission,
AVG(commission_pct) AS avg_ignoring_null,
AVG(NVL(commission_pct, 0)) AS avg_with_zero
FROM employees;The two averages differ. The first averages only the employees with a commission. The second counts employees without commission as zero, so it divides by the number of all rows and gives a lower figure. Which one is correct depends on the question you are asking. Choose deliberately.
NULL in IN and NOT IN
IN is shorthand for a series of OR conditions, and NOT IN is shorthand for a series of AND conditions with <>. NULL in the list makes NOT IN return no rows.
SELECT COUNT(*) AS result
FROM employees
WHERE department_id NOT IN (10, 20, NULL);This returns 0. For any row, one of the tests is department_id <> NULL, which is UNKNOWN. The whole AND can then never be TRUE.
This problem often shows up with subqueries. If the subquery can return NULL, NOT IN returns nothing. Add WHERE column IS NOT NULL inside the subquery, or use NOT EXISTS.
SELECT department_id, department_name
FROM departments
WHERE department_id NOT IN (
SELECT department_id
FROM employees
WHERE department_id IS NOT NULL
);How the pieces fit
The diagram traces how a row meets a WHERE condition that involves a nullable column.
Common errors
- Writing
= NULLor<> NULLinstead ofIS NULLorIS NOT NULL. The query runs and returns no rows. - Forgetting that
<>andNOTfilters drop NULL rows. AddOR column IS NULLwhen you want them. - Adding a NULL column to a number. The whole result is NULL. Wrap the column in
NVLorCOALESCE. - Using
NOT INwith a list or subquery that can contain NULL. - Treating
''as a non-NULL value. In Oracle it is NULL, soWHERE col = ''never matches. - Using
AVGorCOUNT(column)without checking how many NULL values the column holds.
Exercises
Exercise
A query uses WHERE commission_pct <> 0.3. Employees with NULL in commission_pct are missing from the result. Why does this happen, and how do you change the query to include them?
Show answer
For a NULL commission_pct, the comparison NULL <> 0.3 evaluates to UNKNOWN, and WHERE keeps only rows where the condition is TRUE. To include those rows, test for NULL explicitly: WHERE commission_pct <> 0.3 OR commission_pct IS NULL.
Exercise
The table employees has 107 rows and 35 of them have a non-NULL commission_pct. What do COUNT(*) and COUNT(commission_pct) return, and why does AVG(commission_pct) differ from AVG(NVL(commission_pct, 0))?
Show answer
COUNT(*) returns 107 because it counts rows. COUNT(commission_pct) returns 35 because it skips NULL values. AVG(commission_pct) divides by 35 because it ignores NULLs. AVG(NVL(commission_pct, 0)) turns the 72 NULLs into zeros and divides by 107, so it returns a smaller average.
Exercise
Predict the result of this query, then explain it: SELECT COUNT(*) FROM departments WHERE department_id NOT IN (SELECT manager_id FROM departments); Assume at least one row in departments has a NULL manager_id.
Show answer
The query returns 0. The subquery returns at least one NULL, so for every row department_id NOT IN (...) includes a test department_id <> NULL, which is UNKNOWN. The combined AND can never be TRUE. Fix it by adding WHERE manager_id IS NOT NULL to the subquery, or by rewriting the query with NOT EXISTS.