iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL FOREIGN KEY

A foreign key says "this column points at a row in another table". The database makes sure the target actually exists.

Declaring one

SQL
CREATE TABLE orders (
  id          INT PRIMARY KEY,
  customer_id INT NOT NULL,
  total       DECIMAL(10,2),
  CONSTRAINT fk_customer
    FOREIGN KEY (customer_id) REFERENCES customers(id)
);

What it prevents

  • Inserting an order whose customer_id doesn't exist in customers.
  • Deleting a customer who still has orders (unless you set ON DELETE behaviour).

ON DELETE / ON UPDATE

ActionMeans
RESTRICT (default)Block the delete/update if children exist.
CASCADEDelete/update the children too.
SET NULLSet the child column to NULL.
SET DEFAULTSet the child column to its default.
NO ACTIONLike RESTRICT but deferred to commit-time (PG).
SQL
FOREIGN KEY (customer_id) REFERENCES customers(id)
  ON DELETE CASCADE
  ON UPDATE RESTRICT

Performance tip

The parent column being referenced must be indexed (the primary key already is). Most engines also recommend indexing the FK column itself — they don't auto-create that index, and queries that join or check existence on it will scan otherwise.

Tip: If a microservice owns its own table, you can't put a real foreign key across service boundaries. Use a soft FK plus eventual-consistency checks.

Example

Example
ALTER TABLE orders
ADD CONSTRAINT fk_customer
FOREIGN KEY (customer_id) REFERENCES customers(id);
Try it Yourself »

Exercise

Reference the customers table from orders.

FOREIGN KEY (customer_id) customers(id)

Test yourself

Q1. A FK ensures…
Q2. ON DELETE CASCADE means…
Q3. For performance, also index…

Discussion

Loading…