Sub topic 14
Design Choices: When to Allow NULL
This chapter assumes you have read the earlier chapters on three-valued logic, IS NULL, aggregates, NOT IN, outer joins, and constraints. Earlier chapters showed how NULL behaves. This one covers when to let it into a schema at all.
Every nullable column pushes work onto everyone who queries it. Each query must handle UNKNOWN, each aggregate silently skips rows, and each NOT IN becomes a possible trap. Sometimes that cost is worth paying, and sometimes it isn't. The goal is to choose deliberately.
Start From the Meaning of the Column
Ask what a missing value would mean for each column. There are three common answers:
- The value exists but is not known yet. A customer's birth date is one example. NULL fits here.
- The value does not apply to this row. Ada has no manager, so
manager_idis NULL. NULL fits here too. - There is a sensible default. An order quantity of zero or a status of
'new'is a real value. A NULL here only creates a second way to say the same thing.
A useful rule is to make a column NOT NULL unless you can state, in one sentence, what NULL means for it. If you can't, the column probably should not allow NULL.
Defaults Instead of NULL
A DEFAULT clause supplies a value when an INSERT omits the column. Combined with NOT NULL, the column always holds a real value.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
quantity INTEGER NOT NULL DEFAULT 0,
shipped_at TIMESTAMP,
cancelled_at TIMESTAMP,
cancel_reason VARCHAR(100),
CHECK (
(cancelled_at IS NULL AND cancel_reason IS NULL)
OR (cancelled_at IS NOT NULL AND cancel_reason IS NOT NULL)
)
);
INSERT INTO orders (id, customer_id) VALUES (1, 42);The inserted row gets status = 'new' and quantity = 0 without any NULL. The two columns that stay nullable have clear meanings. shipped_at is NULL until the order ships. cancelled_at and cancel_reason are NULL until the order is cancelled.
The CHECK constraint ties the two cancellation columns together. Either both are set or both are NULL. Recall from the constraints chapter that a CHECK passes when its condition is TRUE or UNKNOWN. The condition above tests IS NULL explicitly, so it never evaluates to UNKNOWN and cannot slip through. The database now rejects a cancellation with no reason.
A default is only right when the default value is true. A quantity of 0 is true for a new order. A default birth date of 1900-01-01 is a lie.
Why Sentinel Values Are Usually Worse
A sentinel is a made-up value that stands for "no value", such as -1 for a missing commission, '' for a missing name, or 9999-12-31 for "no end date". Sentinels look like they avoid NULL, but they move the problem into your data.
Suppose the sample employees table stored -1 instead of NULL for Ada and Cy:
| Expression | With NULL | With -1 sentinel |
|---|---|---|
| `SUM(commission)` | 400.00 | 398.00 |
| `AVG(commission)` | 200.00 | 99.50 |
| `MIN(commission)` | 100.00 | -1.00 |
| `WHERE commission < 150` | Ben only | Ada, Ben, Cy |
With NULL, the aggregates skip the missing rows and give the right answer for the known values. With a sentinel, every query must remember to exclude -1. One forgotten filter produces a wrong number with no error. The database also cannot protect you, because -1 passes any numeric CHECK you write.
Sentinels have one narrow legitimate use. A far-future date such as 9999-12-31 for "no end date" lets range queries like WHERE end_date >= CURRENT_DATE work without special handling. If you use this pattern, document it and apply it consistently.
Moving Optional Attributes to Another Table
When a column is NULL for most rows, or belongs to a distinct group of rows, a separate table can remove the NULL. The sample data has this shape. Only Ben and Di have a commission. The following example uses the employees table from the sample data.
CREATE TABLE employee_commissions (
employee_id INTEGER PRIMARY KEY REFERENCES employees (id),
commission NUMERIC(8,2) NOT NULL
);
INSERT INTO employee_commissions (employee_id, commission) VALUES
(2, 100.00),
(4, 300.00);An employee has a commission row or does not. The commission itself can never be NULL. The primary key on employee_id guarantees at most one row per employee. Aggregates over this table need no NULL handling:
SELECT AVG(commission) AS avg_commission
FROM employee_commissions; -- 200.00The trade-off is that NULL comes back whenever you join the tables. This query has to use a LEFT JOIN to keep all employees, and the unmatched rows show NULL:
SELECT e.name,
COALESCE(c.commission, 0) AS commission_or_zero
FROM employees e
LEFT JOIN employee_commissions c ON c.employee_id = e.id
ORDER BY e.id;A separate table is still a good choice in two cases:
- The optional attributes come as a group. For example,
cancelled_at,cancel_reason, andcancelled_byall exist together or not at all. One table with aNOT NULLgroup is easier to keep consistent than three nullable columns plus aCHECK. - The column is mostly empty. A table with many rarely-used nullable columns is hard to read and easy to misuse.
It is a poor choice for a single, commonly queried column such as shipped_at. The extra join and second table cost more than one nullable column.
Nullable Foreign Keys and Self-References
A foreign key column that allows NULL means "this row has no parent". employees.manager_id is the standard example: the top of the hierarchy has no manager.
Foreign key checks skip NULLs. A row with manager_id = NULL is valid without referencing anything, and a non-NULL value must match an existing id. This is useful, but you pay for it in queries. NOT IN over manager_id fails because of the NULL, as the NOT IN chapter showed, and finding the root requires IS NULL.
If a relationship is required, as an order must have a customer, declare the foreign key column NOT NULL. Otherwise the constraint does not enforce the rule you intended.
Adding NOT NULL to an Existing Column
Tightening a column is a three-step change: backfill, set a default, then add the constraint. This example uses PostgreSQL syntax. Other systems use different ALTER forms.
ALTER TABLE orders ADD COLUMN priority INTEGER;
UPDATE orders SET priority = 0 WHERE priority IS NULL;
ALTER TABLE orders ALTER COLUMN priority SET DEFAULT 0;
ALTER TABLE orders ALTER COLUMN priority SET NOT NULL;The backfill must come first. If any NULL remains, SET NOT NULL fails. On a large live table, the backfill and the constraint check can take time and hold locks, so plan the change for a quiet period or in batches.
Choose the backfill value carefully. Setting a missing commission to 0 changes the meaning from "unknown" to "none", and AVG will change as a result. That decision belongs to the data's owner, not to the migration script.
A Decision Path
Common Mistakes
- Allowing NULL by default. In most systems, a column allows NULL unless you say otherwise. Write
NOT NULLexplicitly rather than relying on habit. - Using NULL for two meanings. If NULL could mean "unknown" for some rows and "not applicable" for others, queries cannot tell them apart. Use a separate status column or a different design.
- Using empty strings in place of NULL.
''and NULL behave differently in comparisons, and Oracle treats them as the same, which makes code non-portable. - Nullable columns in a
UNIQUEconstraint. Most systems allow many NULLs in a unique column. If you need at most one row without a value, check how your database handles this. - Forgetting related columns. Nullable columns that depend on each other need a
CHECK, as in theordersexample.
Exercise
A subscriptions table has started_on DATE, ended_on DATE, and end_reason VARCHAR(100). A subscription that is still active has no end date or reason. Write the column definitions so that every subscription must have a start date, and a reason is recorded if and only if an end date is recorded.
Show answer
CREATE TABLE subscriptions (
id INTEGER PRIMARY KEY,
startedon DATE NOT NULL,
endedon DATE,
endreason VARCHAR(100),
CHECK (
(endedon IS NULL AND endreason IS NULL)
OR (endedon IS NOT NULL AND endreason IS NOT NULL)
)
);
`startedon is required, so it is NOT NULL. endedon and endreason are nullable because NULL has one clear meaning: the subscription has not ended. The CHECK tests IS NULL` explicitly, so it never evaluates to UNKNOWN, and it rejects rows where only one of the two columns is set.