Sub topic 1
What NULL means in Oracle
NULL is the most common source of surprising query results in Oracle. Before you use NVL, NVL2, or COALESCE, you need to know exactly what NULL is and what it is not. This chapter builds that model. Later chapters cover comparisons, arithmetic, and the replacement functions in detail.
Prerequisites
This chapter assumes you can:
- Write basic
SELECTstatements withWHEREand column aliases. - Recognize the Oracle data types
NUMBER,VARCHAR2, andDATE. - Use the
DUALtable for quick experiments. - Read simple aggregate queries with
COUNT,SUM, andAVG.
The examples use the EMPLOYEES table from Oracle's sample HR schema, plus one small practice table that the chapter creates.
NULL is the absence of a value
A NULL is a marker that says "there is no value here." It is not a value itself. That has three consequences.
- NULL is not zero. A commission of 0 means the employee earns a commission rate of zero. A NULL commission means no rate is recorded or none applies.
- NULL is not a space or an empty text value. A column containing
' 'holds a one-character string. A column containing NULL holds nothing. - NULL is not equal to anything, including another NULL. Two missing values are not known to be the same.
Because NULL is not a value, it has no data type of its own. Any column of any type can hold NULL, unless a constraint forbids it. A NULL in a NUMBER column and a NULL in a DATE column are both just "nothing stored."
What a NULL can mean
The database stores one marker, but the business meaning varies. When you design queries, ask which meaning applies, because it affects what default you should substitute.
| Meaning | Example |
|---|---|
| Unknown | A customer's birth date was never collected. |
| Not applicable | `commission_pct` for an accountant who is not on commission. |
| Not yet available | A `ship_date` for an order that has not shipped. |
| No matching row | The right-hand columns of an outer join row with no match. |
Oracle cannot tell these cases apart. If you need to distinguish "unknown" from "not applicable," add a status column or use a different design. NULL alone cannot carry that information.
Where NULLs come from
NULLs enter your results in several ways, and not all of them involve a stored NULL.
- Stored NULLs. An
INSERTorUPDATEsets a column to NULL, or leaves it out of the column list and the column has no default. - Outer joins. Unmatched rows return NULL for every column from the optional side.
- Expressions. Many expressions return NULL when an input is NULL. For example,
LENGTH(NULL)is NULL, not 0. - Functions that return NULL by design.
NULLIFandMAXover an empty set are examples. - Empty strings. Oracle treats a zero-length
VARCHAR2value as NULL. This is covered fully in a later chapter, but the practice table below shows it happening.
A practice table
Run this script to create a table that holds NULLs in different ways. The bonus column has a default of 0, which will help show that defaults and NULLs are separate things.
CREATE TABLE null_demo (
id NUMBER PRIMARY KEY,
email VARCHAR2(100) UNIQUE,
nickname VARCHAR2(30),
bonus NUMBER(8,2) DEFAULT 0
);
INSERT INTO null_demo (id, email, nickname, bonus)
VALUES (1, NULL, 'Sam', NULL);
INSERT INTO null_demo (id, email)
VALUES (2, NULL);
INSERT INTO null_demo (id, email, nickname, bonus)
VALUES (3, '[email protected]', '', 0);
COMMIT;
SELECT id, nickname, bonus
FROM null_demo
ORDER BY id;The three rows end up like this:
| id | nickname | bonus | |
|---|---|---|---|
| 1 | NULL | Sam | NULL |
| 2 | NULL | NULL | 0 |
| 3 | [email protected] | NULL | 0 |
Each row teaches something:
- Row 1:
bonusis NULL because the statement named the column and supplied NULL. An explicit NULL overrides the default. - Row 2:
nicknameis NULL because the column was left out and has no default.bonusis 0 because the column was left out and the default applied. - Row 3:
nicknameis NULL because Oracle converts the empty string''to NULL when storing it.
Rows 1 and 2 both have a NULL email, and the UNIQUE constraint accepted both. A unique constraint on a single column allows any number of NULLs, because NULLs are never considered equal to each other.
Seeing NULL in tool output
A NULL looks like an empty cell in many tools, so it is indistinguishable from an empty-looking string. In SQL*Plus and SQLcl, you can change the display text:
SET NULL '<null>'
SELECT id, nickname, bonus
FROM null_demo
ORDER BY id;SQL Developer and other graphical tools usually show (null) in grid output. This setting changes only the display. It does not change the data.
You can also ask Oracle directly with the DUMP function, which describes the internal representation of a value:
SELECT id,
DUMP(nickname) AS nickname_dump,
LENGTH(nickname) AS nickname_length
FROM null_demo
ORDER BY id;For a NULL, DUMP returns the text NULL, and LENGTH returns NULL rather than 0. For the nickname Sam, LENGTH returns 3. A function applied to nothing produces nothing, which is a theme you will see repeatedly.
Testing for NULL
The only reliable way to test for NULL is the IS NULL and IS NOT NULL conditions. The = operator cannot test for NULL. The next chapter explains why in terms of three-valued logic, so for now treat this as a rule.
SELECT id, nickname
FROM null_demo
WHERE nickname IS NULL
ORDER BY id;This returns rows 2 and 3. Writing WHERE nickname = NULL would return no rows, and Oracle would not raise an error. That silent failure makes the mistake hard to notice.
The same applies to the sample data. This counts employees who have no commission rate:
SELECT COUNT(*) AS no_commission
FROM employees
WHERE commission_pct IS NULL;NULL and constraints
Constraints decide whether a column may hold NULL at all.
- A
NOT NULLconstraint rejects any insert or update that would leave the column NULL. - A
PRIMARY KEYimpliesNOT NULLfor each of its columns. - A
UNIQUEconstraint permits NULLs. On a single column, you can store many NULLs. - A
CHECKconstraint passes when its condition evaluates to unknown. A check such asCHECK (bonus >= 0)therefore accepts a NULLbonus. To forbid NULL, combine it withNOT NULL.
The last rule surprises many developers. A CHECK constraint rejects a row only when the condition is false, not when it is unknown.
ALTER TABLE null_demo ADD CONSTRAINT bonus_nonneg CHECK (bonus >= 0);
UPDATE null_demo SET bonus = NULL WHERE id = 2;The update succeeds even though NULL is not greater than or equal to zero in any useful sense. Clean up the experiment afterward by restoring the value:
UPDATE null_demo SET bonus = 0 WHERE id = 2;
COMMIT;Sorting and NULL
Oracle's ORDER BY has to put NULLs somewhere, and it treats NULL as larger than any other value. In an ascending sort, NULLs come last. In a descending sort, they come first.
SELECT employee_id, commission_pct
FROM employees
ORDER BY commission_pct DESC;The employees with no commission appear at the top, which is rarely what a report wants. You can override the default with NULLS FIRST or NULLS LAST:
SELECT employee_id, commission_pct
FROM employees
ORDER BY commission_pct DESC NULLS LAST;DISTINCT and GROUP BY also have a rule of their own: they treat all NULLs as one group, even though = would say they are not equal. So SELECT DISTINCT email FROM null_demo returns one NULL row, not two.
NULL and indexes
A standard B-tree index on a single column does not store entries for rows where that column is NULL. A query such as WHERE nickname IS NULL therefore cannot use a single-column index on nickname and usually scans the table. A composite index does store a row if any of its columns is non-NULL, so adding a constant or a second non-NULL column can make IS NULL searches indexable. This is a performance detail, but it explains why IS NULL on a large table is sometimes slow.
Why this matters for NVL, NVL2, and COALESCE
Because NULL spreads through expressions and has its own rules in comparisons, sorting, and constraints, you often need to turn it into a usable value at the point where you read the data. The three functions in this tutorial do that in different ways:
| Function | Idea |
|---|---|
| `NVL(a, b)` | Use `b` when `a` is NULL. |
| `NVL2(a, b, c)` | Use `b` when `a` is not NULL, and `c` when it is. |
| `COALESCE(a, b, c, ...)` | Use the first argument that is not NULL. |
Each one needs you to decide first what NULL means in your column. Replacing a "not applicable" commission with 0 can be reasonable for a payroll sum. Replacing an "unknown" birth date with today's date would be wrong. The function is simple. The judgment about the default is where the work lies.
Summary of the model
- NULL marks the absence of a value. It is not 0, not a space, and not equal to itself.
- Every data type can hold NULL unless a constraint forbids it.
- NULLs come from stored data, outer joins, expressions, and empty strings.
- Use
IS NULLandIS NOT NULLto test for them. - Constraints, sorting, grouping, and indexes each have their own NULL rules.
Exercise
Using the null_demo table, you run INSERT INTO null_demo (id, email, nickname, bonus) VALUES (4, NULL, NULL, NULL); and then INSERT INTO null_demo (id, email) VALUES (5, NULL);. Both statements succeed. What are the bonus values of rows 4 and 5, and why does the UNIQUE constraint on email not reject these inserts?
Show answer
Row 4 has a NULL bonus because the statement explicitly supplied NULL, which overrides the default. Row 5 has a bonus of 0 because the column was omitted and the default applied. The UNIQUE constraint does not reject the inserts because NULLs are never considered equal to each other, so any number of rows can have a NULL email.
Exercise
A query uses WHERE commission_pct = NULL to find employees with no commission and returns no rows. Rewrite it correctly, and state what the corrected query returns on the sample HR data compared with the original.
Show answer
Use WHERE commission_pct IS NULL. The original returns no rows and raises no error, because = NULL never evaluates to true. The corrected query returns every employee whose commission_pct is NULL, which is most of the table in the sample HR schema.
Exercise
You sort employees with ORDER BY commission_pct DESC and the rows with no commission appear first. Why does this happen, and how do you put them last?
Show answer
Oracle treats NULL as larger than any other value, so a descending sort places NULLs first. Add NULLS LAST, as in ORDER BY commission_pct DESC NULLS LAST.