add-check-without-not-valid
errorADD CHECK without NOT VALID
Why it's unsafe
Adding a CHECK constraint without NOT VALID scans the whole table under an ACCESS EXCLUSIVE lock.
Safe rewrite
Add the CHECK with NOT VALID, then run VALIDATE CONSTRAINT separately (SHARE UPDATE EXCLUSIVE — concurrent reads and writes are allowed).
Example
Try it in the playground →Unsafe
ALTER TABLE orders ADD CONSTRAINT chk_total CHECK (total > 0);Safe
ALTER TABLE orders ADD CONSTRAINT chk_total CHECK (total > 0) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT chk_total;