Systems & Backend

Foreign Key

A column that references another table’s primary key, letting the database enforce that relationships stay valid.

A foreign key is a column whose values must match a primary key in another table, letting the database enforce referential integrity — you cannot have an order pointing to a customer that does not exist, and the database can block or cascade deletes.

Worked example: orders.customer_id is a foreign key to customers.id; the database rejects an order whose customer_id has no matching customer, and can auto-delete or null out orders when a customer is removed (ON DELETE CASCADE / SET NULL). Gotcha: foreign keys add correctness but cost write performance (each insert checks the reference) and complicate sharding (the referenced row may live on another node), which is why many large distributed systems drop database-enforced foreign keys and enforce integrity in the application.