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_iddoesn't exist incustomers. - Deleting a customer who still has orders (unless you set ON DELETE behaviour).
ON DELETE / ON UPDATE
| Action | Means |
|---|---|
RESTRICT (default) | Block the delete/update if children exist. |
CASCADE | Delete/update the children too. |
SET NULL | Set the child column to NULL. |
SET DEFAULT | Set the child column to its default. |
NO ACTION | Like 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)
Ten letters.
Discussion
Loading…