Blocking Pattern (Avoid in Production)
ALTER TABLE billing.orders ADD CONSTRAINT fk_orders_account
FOREIGN KEY (account_id) REFERENCES billing.accounts (id);
Zero-Downtime Safe Rewrite
SET lock_timeout = '2s';
ALTER TABLE billing.orders ADD CONSTRAINT fk_orders_account
FOREIGN KEY (account_id) REFERENCES billing.accounts (id) NOT VALID;
ALTER TABLE billing.orders VALIDATE CONSTRAINT fk_orders_account;
Production Rollout Notes
- NOT VALID enforces the constraint immediately for all new/updated rows.
- VALIDATE CONSTRAINT scans existing rows under SHARE UPDATE EXCLUSIVE without blocking reads or writes.