What is a FOREIGN KEY in PostgreSQL?

Answer

A FOREIGN KEY enforces referential integrity between two tables — it ensures that a value in one table corresponds to an existing value in another. Syntax: REFERENCES parent_table(column). Example: CREATE TABLE orders (id SERIAL PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id));. Actions on referenced row deletion/update: ON DELETE CASCADE (delete child rows), ON DELETE SET NULL (null the FK), ON DELETE RESTRICT (default — prevent deletion), ON DELETE NO ACTION (deferred check). Foreign keys can cause performance issues if the referencing column isn't indexed — always add an index on FK columns. Disable FK checks temporarily (per session) is not directly supported; you can use SET session_replication_role = replica;.