Foreign Key NOT VALID Online Add

Add a foreign key online with NOT VALID to skip scanning existing rows, then validate it later under a light lock that never blocks reads or writes.

SqlData Integrity

Code

snippet
-- 大表加外键:直接 ADD CONSTRAINT 要全表扫描验证存量行,长时间持锁。
-- 两步走:NOT VALID 先上约束(不扫旧行,只拦新写入),低峰期再验证。
ALTER TABLE order_items
    ADD CONSTRAINT order_items_order_fk
    FOREIGN KEY (order_id) REFERENCES orders (id)
    NOT VALID;

-- 从这一刻起新写入已被拦截:order_id 不存在会立即报错
-- INSERT INTO order_items (order_id, sku) VALUES (999999, 'desk-lamp');

-- pg_constraint.convalidated 记录约束是否已验证存量数据
SELECT conname, convalidated FROM pg_constraint
WHERE conname = 'order_items_order_fk';

-- 低峰期补验证:VALIDATE CONSTRAINT 只扫存量行,
-- 持 SHARE UPDATE EXCLUSIVE 锁,不阻塞读写;验证失败时约束保持 NOT VALID
ALTER TABLE order_items VALIDATE CONSTRAINT order_items_order_fk;

-- 验证完成后 convalidated 变为 true,存量行与新写入同样受约束保护
SELECT conname, convalidated FROM pg_constraint
WHERE conname = 'order_items_order_fk';

What the code does

Several statements share this file — SELECT / ALTER, with pg_constraint among the objects involved.

Mechanically, the statements are built from: a WHERE clause that narrows down the rows one statement touches; a foreign-key REFERENCES guard keeping rows attached to the parent table.

Applying it

Run the statement against the pg_constraint table.

Statements that matter

SELECT conname, convalidated FROM pg_constraint
WHERE conname = 'order_items_order_fk';
ALTER TABLE order_items
ADD CONSTRAINT order_items_order_fk
FOREIGN KEY (order_id) REFERENCES orders (id)
NOT VALID;
ALTER TABLE order_items VALIDATE CONSTRAINT order_items_order_fk;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `pg_constraint`.