Sub topic 8
NULLs and what B-tree indexes store
This chapter assumes you can read a basic execution plan, know what a B-tree index is, and have seen the ideas of access predicates and function-free predicates from the earlier chapters. Here you will learn one rule that surprises many developers: Oracle B-tree indexes do not store every row. You will also learn how that rule affects IS NULL, IS NOT NULL, NOT IN, and the choices you make when you design an index.
The rule: all-NULL entries are not stored
A B-tree index in Oracle leaves out a row when every indexed column in that row is NULL. If at least one indexed column has a value, the row is stored.
This follows from how Oracle treats NULL in an index key. A NULL is stored as a missing value inside a key that has other values, but a key made only of NULLs has nothing to sort on, so Oracle skips it.
| Index definition | Row values | Row stored in index? |
|---|---|---|
| `(commission_pct)` | `commission_pct = 0.2` | Yes |
| `(commission_pct)` | `commission_pct IS NULL` | No |
| `(commission_pct, salary)` | `commission_pct IS NULL`, `salary = 5000` | Yes |
| `(commission_pct, salary)` | both NULL | No |
The consequence is simple. A search for IS NULL on a single-column index is asking for rows that the index does not contain. The index cannot answer it, so Oracle reads the table instead.
Why IS NULL cannot use a single-column index
Consider this table and index.
CREATE INDEX employees_commission_ix ON employees (commission_pct);
SELECT employee_id
FROM employees
WHERE commission_pct IS NULL;The optimizer cannot use employees_commission_ix for this query. The index holds only employees with a commission. Every row you want is missing from it. If Oracle used the index, it would return no rows or the wrong rows, so the optimizer chooses a full table scan.
You can confirm this with the plan tools from the earlier chapter.
EXPLAIN PLAN FOR
SELECT employee_id
FROM employees
WHERE commission_pct IS NULL;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for TABLE ACCESS FULL on EMPLOYEES. The exact plan depends on your data and statistics, but the index named above will not appear as an access path for this predicate.
IS NOT NULL works the other way
IS NOT NULL asks for rows that the index does store. A single-column index on commission_pct can therefore be used for it.
SELECT employee_id
FROM employees
WHERE commission_pct IS NOT NULL;Whether Oracle actually chooses the index depends on selectivity. If most rows have a commission, a full scan is cheaper. If only a few do, an index range scan, or a fast full scan of the index when the query needs only indexed columns, is a good choice. The chapter on selectivity covers that trade-off.
Likewise, a comparison such as commission_pct > 0.1 can use the index. Any comparison with a value is false or unknown for NULL, so rows with a NULL can never match, and the index does not need them.
Making IS NULL searchable
If you need to search for NULLs often, you have two ways to put those rows in an index.
Add a constant column
Add a second column that is never NULL. Every row then has at least one non-NULL indexed value, so every row is stored.
-- A B-tree index does not store entries whose indexed columns are all NULL
CREATE INDEX employees_commission_ix ON employees (commission_pct);
-- Cannot be answered from that index
SELECT employee_id FROM employees WHERE commission_pct IS NULL;
-- Adding a constant second column makes every row appear in the index
CREATE INDEX employees_commission_nn_ix ON employees (commission_pct, 0);
SELECT employee_id FROM employees WHERE commission_pct IS NULL;The constant 0 is an expression, so Oracle builds this as a function-based index. It costs one extra byte per entry, which is small. The query now has an index that contains the NULL rows, and the optimizer can consider an index range scan.
Both indexes in the example above cannot exist on the same column list in some situations, because Oracle rejects two indexes on the same columns in the same order. They differ here because the second contains an extra expression, but you would normally keep only the second one.
Use a real NOT NULL column
A cleaner option is to add a column that already exists and is declared NOT NULL, such as a primary key or a creation date, as a trailing column of a composite index.
CREATE INDEX employees_commission_id_ix
ON employees (commission_pct, employee_id);This index serves IS NULL searches, and it also serves queries that filter on commission_pct and then look at employee_id. Because the extra column has a purpose, this is usually better than a constant.
The constant trick does the job but adds an index that serves only one purpose. Prefer the real column when your queries can use it.
NOT NULL constraints help the optimizer
A NOT NULL constraint tells Oracle that every row will appear in an index on that column. That has two effects.
IS NULLon a constrained column is known to match nothing, and the optimizer can use this fact.- The optimizer can answer a query such as
SELECT COUNT(*) FROM employeesby scanning a smaller index, but only if it knows the index contains every row. An index on a nullable column cannot be used for this, because it might be missing rows. An index on aNOT NULLcolumn can.
If a column should never be empty, declare it NOT NULL. This is a data quality rule and a performance aid at once.
A query that fails silently: NOT IN with NULLs
NULL also changes the meaning of NOT IN. This is a correctness problem more than an index problem, but it affects the plans Oracle can pick.
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);If orders.customer_id contains even one NULL, the NOT IN comparison yields unknown for every outer row, and the query returns no rows. Oracle must also handle that possibility, which limits the join methods it can use. If the column is NOT NULL, or the subquery excludes NULLs, Oracle can use an anti-join, which is usually much faster.
Two safe rewrites are:
-- NOT EXISTS ignores NULLs in the way most people expect
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
-- Or remove NULLs from the subquery
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
WHERE customer_id IS NOT NULL
);What each case does
The diagram summarizes how Oracle treats a predicate on a single-column B-tree index.
Gotchas
- Empty strings are NULL. In Oracle,
''is stored as NULL inVARCHAR2columns. A row with an empty string follows the rules above, andcolumn = ''never matches anything, because comparing with NULL is never true. - Composite indexes need only one non-NULL column. A row with
NULLin the leading column but a value in a later column is stored. A search forleading_col IS NULL AND second_col = 5can use the index. The all-NULL rule applies to the whole key. - Bitmap indexes differ. Bitmap indexes do store NULLs, so
IS NULLcan use them. They suit read-heavy warehouse tables, not busy OLTP tables, so they are not a general fix. - Unique indexes allow many NULLs on a single column. Because all-NULL keys are not stored, they never collide. For a multi-column unique index, rows where any column is NULL and other columns match can behave differently from what you expect, so test your case.
- Check the plan. Do not rely on rules alone. The optimizer may reject an index for other reasons, so confirm with
DBMS_XPLAN.
Summary
A B-tree index omits rows whose indexed columns are all NULL. So IS NULL cannot use a single-column index, while IS NOT NULL and value comparisons can. To search for NULLs, add a non-null column to the index, either a constant or a useful real column. Declare columns NOT NULL where the data allows, and write NOT IN carefully or use NOT EXISTS.
Exercise
A table shipments has a nullable column delivered_on with a single-column B-tree index. The query SELECT shipment_id FROM shipments WHERE delivered_on IS NULL runs a full table scan, and only 0.5% of rows are undelivered. Why can the index not be used, and how would you change the index so that it can?
Show answer
A B-tree index does not store rows where all indexed columns are NULL, so the undelivered rows are missing from the index and it cannot answer the query. Recreate the index with a non-null second column, for example CREATE INDEX shipments_delivered_ix ON shipments (delivered_on, shipment_id) if shipment_id is NOT NULL (or use a constant such as (delivered_on, 0)). Every row then has a non-null indexed value, so undelivered rows are stored, and the optimizer can use an index range scan because the predicate is selective.
Exercise
A query SELECT c.customer_id FROM customers c WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o) returns no rows, although some customers have no orders. What is the likely cause, and what are two fixes?
Show answer
At least one row in orders has a NULL customer_id. NOT IN then evaluates to unknown for every customer, so no row qualifies. One fix is to add WHERE o.customer_id IS NOT NULL to the subquery. The other is to rewrite the query with NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id).