Sub topic 8
NULLs and What B-Tree Indexes Store
This chapter assumes you know basic SELECT and WHERE syntax, Oracle data types, and the purpose of an index. The key rule is simple:
> An Oracle B-tree index does not store a row when every indexed column is NULL.
For a single-column index, this means rows with a NULL value are absent from the index. Oracle cannot find those rows by scanning that index.
CREATE INDEX employees_commission_ix
ON employees (commission_pct);
-- The index contains no entry for rows where commission_pct is NULL.
SELECT employee_id
FROM employees
WHERE commission_pct IS NULL;Oracle may choose a full table scan for the second query because the index has no entries for the requested rows. The predicate is correct. The index simply cannot provide those entries.
Use `IS NULL`, not equality
NULL means “unknown” or “missing,” not a value that compares equal to another NULL. Therefore, use IS NULL and IS NOT NULL.
-- Correct
SELECT employee_id
FROM employees
WHERE commission_pct IS NULL;
-- Correct
SELECT employee_id
FROM employees
WHERE commission_pct IS NOT NULL;
-- Does not find NULL values
SELECT employee_id
FROM employees
WHERE commission_pct = NULL;The expression commission_pct = NULL evaluates to unknown for every row, so it returns no rows.
Make NULL rows visible to an index
Add a constant expression as another indexed column. Every row then has a non-NULL indexed value in the constant position, so rows with a NULL commission value receive index entries.
CREATE INDEX employees_commission_nn_ix
ON employees (commission_pct, 0);
SELECT employee_id
FROM employees
WHERE commission_pct IS NULL;The constant does not provide useful search information by itself. It makes the composite index contain rows that would otherwise have all indexed columns set to NULL. Verify the chosen plan with DBMS_XPLAN.DISPLAY, because Oracle still compares the index cost with a table scan.
NULLs in composite indexes
For an index on (department_id, commission_pct), Oracle stores a row if at least one indexed column is non-NULL.
| Indexed values | Stored in `(department_id, commission_pct)`? |
|---|---|
| `(10, 0.15)` | Yes |
| `(10, NULL)` | Yes |
| `(NULL, 0.15)` | Yes |
| `(NULL, NULL)` | No |
The leading-column rule still applies. An index entry may exist for (NULL, 0.15), but searching efficiently by commission_pct alone generally cannot use a normal range scan on this index because department_id is the leading column.
Exercise
Why does a single-column B-tree index on commissionpct not find rows where commissionpct IS NULL, and what index design can make those rows searchable?
Show answer
Oracle omits entries whose indexed value is NULL. A composite index such as (commission_pct, 0) adds a non-NULL constant, causing every row to have an index entry.