NOT NULL & DEFAULT in Depth in SQL
Every column deserves an explicit NULL verdict
Nullable-by-default means every column is a NULL decision you must make: ids, names, amounts are NOT NULL; optional notes stay nullable. DEFAULT supplies omitted-insert values (0, '', now(), generated expressions) so writers skip repetition. Required facts + defaults close the mystery-NULL factory;ower layers (CHECK) then assume presence.
Verdict per column
Ids/names/amounts NOT NULL; notes nullable. Implicit nullability breeds mystery NULLs.
DEFAULT fills omission
0, now(), generated — writers skip repetition, old rows stay valid on ADD.
Backfill then constrain
Full tables: nullable → batch-fill → SET NOT NULL. Direct fails or long-locks.
Pair with CHECK
CHECK lets NULLs through (UNKNOWN). NOT NULL closes the loophole.
1CREATE TABLE staff (2 id INT PRIMARY KEY,3 name TEXT NOT NULL,4 bonus NUMERIC(12,2) DEFAULT 0,5 created_at TIMESTAMPTZ NOT NULL DEFAULT now()6);
| column | rule |
|---|---|
| name | NOT NULL — required |
| bonus | DEFAULT 0 |
| created_at | DEFAULT now() |
Inserting (1, 'Ada') fills bonus 0 and now() automatically. Inserting NULL name fails fast with a clear error instead of a downstream mystery.
Staff DDL with verdicts
Required facts + filled optionals.
1CREATE TABLE staff (2 id INT PRIMARY KEY,3 name TEXT NOT NULL,4 bonus NUMERIC DEFAULT 0,5 created_at TIMESTAMPTZ NOT NULL DEFAULT now()6);
| column | rule |
|---|---|
| name | NOT NULL |
| bonus | DEFAULT 0 |
| created_at | NOT NULL + now() |
CHECK needs NOT NULL
NULL sails through CHECK alone.
1salary NUMERIC CHECK (salary >= 0) -- NULL passes!2name TEXT NOT NULL CHECK (length(name) > 0) -- closed
| form | effect |
|---|---|
| CHECK alone | NULL passes (UNKNOWN) |
| CHECK + NOT NULL | enforced |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.