NOT NULL Constraint
Last updated: 2026-11-04
NOT NULL Constraint
NOT NULL declares that a column always holds a value. It is more precise than CHECK and lets the planner exploit the guarantee, so 'this column cannot be empty' should be expressed with NOT NULL rather than `CHECK (col IS NOT NULL)`. In PostgreSQL 18, NOT NULL is a first-class entry in pg_constraint and can be found with contype = 'n'.
| Kind | constraint |
|---|---|
| Example Language | SQL |
📝 Syntax
Column level: `column_name type NOT NULL`
After creation: `ALTER TABLE t ALTER COLUMN c SET NOT NULL`
Remove: `ALTER TABLE t ALTER COLUMN c DROP NOT NULL`
⚙️ Parameters
| column_name | The column that may not be NULL. NOT NULL is a column-level constraint only; the table-level form `NOT NULL (col)` is a syntax error. |
|---|
Returns:NOT NULL has no return value. On violation PostgreSQL raises `null value in column "..." of relation "..." violates not-null constraint`.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
SELECT 'NOT NULL constraints on accounts' AS step,
(SELECT string_agg(conname, ', ' ORDER BY conname) FROM pg_constraint
WHERE conrelid='accounts'::regclass AND contype='n') AS result
UNION ALL SELECT 'insert owner = NULL',
(SELECT pg_try('INSERT INTO accounts VALUES (3,NULL,10.00)'))
UNION ALL SELECT 'rows stored',
(SELECT count(*)::TEXT FROM accounts)
step | result
----------------------------------+----------------------------------------------------------------------------------
NOT NULL constraints on accounts | accounts_account_id_not_null, accounts_balance_not_null, accounts_owner_not_null
insert owner = NULL | null value in column "owner" of relation "accounts" violates not-null constraint
rows stored | 2
(3 rows)
📌 Key Points
- NOT NULL can only be written as a column constraint; `ALTER TABLE ... ADD CONSTRAINT ... NOT NULL (col)` is a syntax error.
- Since PostgreSQL 18, NOT NULL appears in pg_constraint with contype = 'n' and can be queried alongside other constraints.
- Before adding NOT NULL to a populated column, make sure it holds no NULLs or the ALTER will fail.
- Combining a default with NOT NULL is common: `balance NUMERIC(12,2) NOT NULL DEFAULT 0`.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhat is the difference between NOT NULL and CHECK (col IS NOT NULL)?
ABoth reject NULLs, but NOT NULL is a distinct constraint kind that the planner can use directly and that appears as its own row in pg_constraint. A CHECK is just a boolean expression, with less precise semantics.
QHow do I add NOT NULL to a column that already contains NULLs?
AResolve the NULL rows first — UPDATE them with a default value or DELETE them — then add the constraint. A common sequence is `ALTER TABLE t ALTER COLUMN c SET DEFAULT 0`, `UPDATE t SET c = 0 WHERE c IS NULL`, then SET NOT NULL.