Add CHECK Constraint With NOT VALID

Add a CHECK constraint online with NOT VALID so existing rows stay unscanned, then enforce them later with VALIDATE CONSTRAINT.

SqlData Integrity

Code

snippet
-- 在线加 CHECK:NOT VALID 只约束新写入、不扫描存量行,DDL 秒级完成
ALTER TABLE invoices
  ADD CONSTRAINT chk_invoice_total_non_negative
  CHECK (total_cents >= 0 AND currency IS NOT NULL) NOT VALID;

-- 存量脏数据会让校验失败:先清点,修完再验证
SELECT count(*) FROM invoices WHERE total_cents < 0 OR currency IS NULL;

-- 修复存量行:空币种补默认值,之后 VALIDATE 才可能通过
UPDATE invoices SET currency = 'USD' WHERE currency IS NULL;

-- NOT VALID 之后新写入立即受约束:负数总额当场被拒绝
INSERT INTO invoices (invoice_id, total_cents, currency)
VALUES (9001, -500, 'USD');

-- VALIDATE CONSTRAINT 用 SHARE UPDATE EXCLUSIVE 锁,不阻塞并发读写
ALTER TABLE invoices VALIDATE CONSTRAINT chk_invoice_total_non_negative;

How the snippet works

What runs here is SELECT / INSERT / UPDATE / ALTER — invoices are the objects involved.

Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns.

Applying it

The invoices table is the working surface here.

Statements that matter

SELECT count(*) FROM invoices WHERE total_cents < 0 OR currency IS NULL;
UPDATE invoices SET currency = 'USD' WHERE currency IS NULL;
INSERT INTO invoices (invoice_id, total_cents, currency)
VALUES (9001, -500, 'USD');

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`invoices`.