How to Add a Foreign Key in PostgreSQL
Last updated July 25, 2026 · By the SaturnSQL team
Use ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY ... REFERENCES. On big tables, add it NOT VALID first (instant, checks only new rows), then VALIDATE CONSTRAINT separately, which checks existing rows without blocking writes.
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id);Big tables: NOT VALID, then VALIDATE
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;ON DELETE CASCADE or ON DELETE SET NULL controls what happens to child rows. Also index the referencing column (customer_id); Postgres does not do that automatically, and its absence makes deletes on the parent table slow.
Run this in SaturnSQL
SaturnSQL is a browser-based SQL editor for teams: shared query library, schema-aware autocomplete, and scheduled exports to Google Sheets and Slack.
Try it free