Foreign Key

A foreign key is an attribute (or set of attributes) in one table that references the Primary Key of another table. It enforces Referential Integrity — ensuring that relationships between tables remain consistent. A foreign key value must either match an existing primary key value in the referenced table or be NULL (if the column allows it).

Syntax

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INT NOT NULL REFERENCES customers(id),
    product_id INT NOT NULL REFERENCES products(id),
    quantity INT NOT NULL
);

Naming convention from Database Constraints: use <table_name>_id format (e.g., customer_id) so the reader immediately knows which table is referenced.

Referential Actions

What happens when the referenced Primary Key row is deleted or updated. See Database Constraints for details:

ActionON DELETEON UPDATE
RESTRICT (default)Block the deleteBlock the update
CASCADEDelete child rowsUpdate child FK values
SET NULLSet FK to NULLSet FK to NULL
SET DEFAULTSet FK to default valueSet FK to default value
CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INT REFERENCES customers(id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

Foreign Keys and Performance

  • Foreign key columns should always be indexed — without an Index, cascading deletes and joins require full table scans
  • PostgreSQL does not auto-index foreign keys (unlike primary keys). Always create the index manually:
CREATE INDEX idx_orders_customer_id ON orders(customer_id);