Glossary

foreign key

A foreign key is a Postgres constraint that forces a column value to match a row in a referenced table, enforcing referential integrity between them.

A foreign key is a constraint that forces a column's value to match an existing row in a referenced table, so a child row can never point at a parent that does not exist.

You declare one with REFERENCES, naming the parent table and its key column. Postgres then rejects any INSERT or UPDATE that would leave the child pointing at a missing parent, and (depending on the referential action) blocks or cascades deletes of a parent that still has children.

CREATE TABLE posts (
  id       bigint PRIMARY KEY,
  author_id bigint NOT NULL
    REFERENCES users (id) ON DELETE CASCADE
);

Here posts.author_id must equal some users.id. Inserting a post before its author exists raises foreign key violation: insert or update on table "posts" violates foreign key constraint.

This is why data has to move in dependency order. If you copy posts before users, every row fails the check. A migration walks the foreign-key graph, loads parent tables first, then children, and defers or drops-and-recreates constraints only when a cycle makes a strict order impossible. After the rows land, identity and serial columns need a sequence resync so new inserts do not collide with copied IDs.

Constraints are part of the schema, not the data, so they are recreated during schema replay — before any rows are inserted, so the destination validates referential integrity as the data arrives.

Related terms