Set Not Null Backed By Validated Check
Adding a NOT VALID check and validating it first lets SET NOT NULL skip the table scan on PostgreSQL 12+, turning a long lock into metadata work.
Code
-- Goal: make email NOT NULL on a table already holding millions of rows,
-- a direct ALTER COLUMN SET NOT NULL scans the whole table under a long-held lock.
-- The PG 12+ way: attach a NOT VALID CHECK declaring the same fact first
ALTER TABLE profiles ADD CONSTRAINT profiles_email_required
CHECK (email IS NOT NULL)
NOT VALID;
-- VALIDATE CONSTRAINT takes only a shared lock to verify existing rows, with reads and writes allowed throughout
ALTER TABLE profiles VALIDATE CONSTRAINT profiles_email_required;
-- The planner already knows email has no NULLs: SET NOT NULL skips the table scan and completes instantly
ALTER TABLE profiles ALTER COLUMN email SET NOT NULL;
-- Once the CHECK has served its purpose, drop it; the NOT NULL stands on its own
ALTER TABLE profiles DROP CONSTRAINT profiles_email_required;How it works
The statement is ALTER.
Mechanically, the statement is built from: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns.
The four statements run in a fixed order. ADD CONSTRAINT … NOT VALID registers profiles_email_required without touching existing rows, so it returns immediately even on a table holding millions of rows. VALIDATE CONSTRAINT then proves that fact against the stored data under a lock that still allows reads and writes throughout. Only after that proof does ALTER COLUMN email SET NOT NULL run — the planner can rely on the validated constraint instead of re-scanning profiles, which turns the historically slow step into an instant metadata change. Dropping profiles_email_required at the end removes the auxiliary CHECK; the NOT NULL it was built to back remains in force.
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.