skip to content

NOT NULL, CHECK and UNIQUE

rules the database enforces so your app doesn't have to remember, plus NULLS NOT DISTINCT.

address
everything.design.constraints
part
part 7, schema design
chapter
chapter 3 of 13
reading time
9 min

a constraint is a rule the database checks on every write, so no code path can forget it: NOT NULL, CHECK (a boolean expression per row), UNIQUE, plus primary keys, foreign keys and exclusion constraints. a row that breaks one is refused with an error and a SQLSTATE.

UNIQUE ignores NULLs unless you say NULLS NOT DISTINCT (postgres 15). a deferrable constraint can wait until the end of the statement or the transaction. and on a big table you add one NOT VALID first, then VALIDATE it without blocking writes.

the picture

you know the validation code in every app: "name can't be blank", "price must be positive", "this email is taken"? it lives in a form, then an API, then a batch import someone writes on a friday, and one of them forgets. the database is the only place every write goes through.

think of a bouncer at the one door of a club (the table). the app's checks are friendly signs in the street; useful, but anyone can walk past them. the bouncer checks every single person, including the ones who came in through the back with a script.

rule =
products.sql
  1. 1INSERT INTO products VALUES (2, 'TEA-02', NULL, 5.00, NULL, 'A1');
ERROR: null value in column "name" of relation "products" violates not-null constraintSQLSTATE 23502

a product with no name. NOT NULL turns it away: 23502.

real output, postgres 18.6 (PGlite 0.5.12) · constraints
one products table with a rule on every column that needs one. pick a rule and see the row it turns away, with the real error and its SQLSTATE. two NULLs is the surprise: plain UNIQUE lets them both in.

every error names the constraint, and postgres names constraints for you (products_price_check, products_sku_key) unless you name them yourself with CONSTRAINT name. name them: the name is what your app catches and what shows up in logs.

CHECK is "not false"

a CHECK is any boolean expression over the row's own columns. it can span columns:

sqlempty db
CREATE TABLE stays (
  guest     text NOT NULL,
  check_in  date NOT NULL,
  check_out date NOT NULL,
  CONSTRAINT stays_order CHECK (check_out > check_in)
);
INSERT INTO stays VALUES ('ada', '2026-03-05', '2026-03-02');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · ERROR 23514
ERROR 23514: new row for relation "stays" violates check constraint "stays_order"
DETAIL: Failing row contains (ada, 2026-03-05, 2026-03-02).
predict the output
sql
CREATE TABLE items (qty int CHECK (qty > 0));
INSERT INTO items VALUES (NULL);
sqlempty db
CREATE TABLE items (qty int CHECK (qty > 0));
INSERT INTO items VALUES (NULL);
SELECT qty IS NULL AS stored_a_null FROM items;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 1
stored_a_nullbool
t
(1 row)

the three-valued logic asymmetry, in one table. two other limits: a CHECK sees only the row being written (not other rows, not other tables, that's what UNIQUE, foreign keys and triggers are for), and any function it calls should be IMMUTABLE, because postgres never re-checks old rows when the function's answer changes. and when the same CHECK belongs on many columns, give it a name as a type: that's a domain (booleans, enums and domains).

UNIQUE and its NULLs

UNIQUE is enforced by a unique b-tree index (postgres builds it for you). the figure showed the catch: by default two NULLs aren't equal, so they don't collide, and a UNIQUE column can hold any number of them. that's what the standard says, and usually what you want: two customers with no phone number aren't duplicates.

when NULL is a real value ("no shelf assigned", and only one product may be unassigned), UNIQUE NULLS NOT DISTINCT pg 15+ makes NULLs collide too. before 15, the workaround was a unique index on coalesce(col, ''), or a partial unique index WHERE col IS NULL on a constant.

for overlap rather than equality (two bookings of one room on the same night) the generalisation of UNIQUE is an exclusion constraint, EXCLUDE USING gist (room WITH =, nights WITH &&), covered in range types, with postgres 18's shorthand in temporal keys.

when the check happens

postgres checks a NOT NULL, CHECK or plain UNIQUE constraint row by row, as each row is written. for UNIQUE that has an odd consequence: a statement that would end up fine can fail halfway through.

unique =
playlist.sql
  1. 1UPDATE plain SET pos = pos + 1;
ERROR: duplicate key value violates unique constraint "plain_pos_key"SQLSTATE 23505

plain UNIQUE is checked row by row. moving 1 to 2 collides with the 2 that hasn't moved yet.

real output, postgres 18.6 (PGlite 0.5.12) · constraints
a playlist with unique positions; shift every song down one. plain UNIQUE fails, because the first row moves onto a position the next row hasn't left yet. DEFERRABLE checks once the statement is done. INITIALLY DEFERRED waits for COMMIT, and a duplicate still there at COMMIT kills the transaction.

DEFERRABLE alone means "initially immediate": checked at the end of each statement. a transaction can push it to COMMIT with SET CONSTRAINTS name DEFERRED. INITIALLY DEFERRED makes COMMIT the default. NOT NULL and CHECK are never deferrable; UNIQUE, PRIMARY KEY, EXCLUDE and FOREIGN KEY can be. foreign keys are where deferring earns its keep, for rows that point at each other (foreign keys).

the cost: a deferrable unique index can't be an ON CONFLICT arbiter, and checking later means postgres keeps a list of rows to recheck. make a constraint deferrable when you need it, not by default.

adding a constraint to a table that's live

ALTER TABLE ... ADD CONSTRAINT ... CHECK scans the whole table to prove every row passes, under an ACCESS EXCLUSIVE lock: no reads, no writes, for as long as the scan takes. on a big table that's an outage, and a queue of blocked queries behind it (the lock queue).

the fix is two steps. NOT VALID adds the rule without looking at old rows; new and updated rows are checked from that moment. VALIDATE CONSTRAINT later scans the old rows under a weaker lock. here are both locks, read from pg_locks:

sqlempty db
CREATE TABLE payments (id int PRIMARY KEY, amount numeric(10,2));
INSERT INTO payments VALUES (1, 20.00), (2, -3.00), (3, 7.50);
 
BEGIN;
ALTER TABLE payments ADD CONSTRAINT payments_positive CHECK (amount > 0) NOT VALID;
SELECT 'add NOT VALID' AS step, mode FROM pg_locks WHERE relation = 'payments'::regclass;
COMMIT;
 
UPDATE payments SET amount = 3.00 WHERE id = 2;
 
BEGIN;
ALTER TABLE payments VALIDATE CONSTRAINT payments_positive;
SELECT 'validate' AS step, mode FROM pg_locks WHERE relation = 'payments'::regclass;
COMMIT;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 3
#3 · BEGIN
#4 · ALTER TABLE
#5 · SELECT 1
steptextmodetext
add NOT VALIDAccessExclusiveLock
(1 row)
#6 · COMMIT
#7 · UPDATE 1
#8 · BEGIN
#9 · ALTER TABLE
#10 · SELECT 1
steptextmodetext
validateShareUpdateExclusiveLock
(1 row)
#11 · COMMIT

the ADD still takes ACCESS EXCLUSIVE, but only for an instant, since it doesn't scan. VALIDATE takes SHARE UPDATE EXCLUSIVE, which lets reads and writes carry on while it scans. had row 2 still been negative, VALIDATE would have failed and named the constraint, and the constraint would have stayed in place, NOT VALID, still checking new rows.

hover a stage.

the safe migration, in three steps. the expensive scan happens in the step that doesn't block writes.

pg 18+ NOT NULL joins in. postgres 18 stores NOT NULL constraints in pg_constraint with names, and lets you add one NOT VALID:

sqlempty db
CREATE TABLE signups (id int, email text);
INSERT INTO signups VALUES (1, 'ada@example.com'), (2, NULL);
 
ALTER TABLE signups ADD CONSTRAINT signups_email_nn NOT NULL email NOT VALID;
INSERT INTO signups VALUES (3, NULL);
ALTER TABLE signups VALIDATE CONSTRAINT signups_email_nn;
 
SELECT conname, contype, convalidated FROM pg_constraint WHERE conrelid = 'signups'::regclass;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 2
#3 · ALTER TABLE
#4 · ERROR 23502
ERROR 23502: null value in column "email" of relation "signups" violates not-null constraint
DETAIL: Failing row contains (3, null).
#5 · ERROR 23502
ERROR 23502: column "email" of relation "signups" contains null values
#6 · SELECT 1
connamenamecontypecharconvalidatedbool
signups_email_nnnf
(1 row)

the new NULL is refused, the old one is still there, and VALIDATE says so. fix row 2 and VALIDATE goes through.

constraints that aren't checked

also new in pg 18+: CHECK and foreign key constraints can be declared NOT ENFORCED. the constraint exists in the catalog, documents the rule, and checks nothing:

sqlempty db
CREATE TABLE readings (id int, celsius numeric CONSTRAINT plausible CHECK (celsius BETWEEN -90 AND 60) NOT ENFORCED);
INSERT INTO readings VALUES (1, 400);
SELECT conname, conenforced, convalidated FROM pg_constraint WHERE conrelid = 'readings'::regclass;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 1
#3 · SELECT 1
connamenameconenforcedboolconvalidatedbool
plausibleff
(1 row)

400 degrees went in. it's for rules enforced somewhere else (an upstream system, a loader) that you still want written down, for people and for tools. in 18 a foreign key can later be switched with ALTER CONSTRAINT ... ENFORCED (which checks the existing rows), but a CHECK can't, so a NOT ENFORCED CHECK becomes enforced only by dropping it and adding it again:

sqlempty db
CREATE TABLE readings (id int, celsius numeric CONSTRAINT plausible CHECK (celsius BETWEEN -90 AND 60) NOT ENFORCED);
ALTER TABLE readings ALTER CONSTRAINT plausible ENFORCED;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · ERROR 42809
ERROR 42809: cannot alter enforceability of constraint "plausible" of relation "readings"

keylines

  • constraints are checked on every write, so no code path can skip them.
  • a CHECK refuses false, not NULL: add NOT NULL when NULL isn't allowed.
  • UNIQUE lets many NULLs in; NULLS NOT DISTINCT (15+) makes them collide.
  • DEFERRABLE moves the check to the end of the statement, INITIALLY DEFERRED to COMMIT.
  • on a big table: ADD ... NOT VALID, fix the rows, then VALIDATE without blocking writes.