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.
Code
-- 在线加 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What objects does the SQL involve?
- `invoices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.