Data

foreign key

A foreign key is a column in one table that points to the primary key of another — it's how a database links rows together. An order, for example, holds the id of the customer who placed it; that customer_id is a foreign key, a little arrow from the order over to the right person.

This is the trick that turns separate tables into a connected web. You don't repeat the customer's whole name and address on every order — you just store their id once and reach for it whenever you need them. Follow the arrow and you can jump from an order to its customer, or gather all orders belonging to one customer.

The database can guard these links for you: it'll refuse to let an order reference a customer who doesn't exist, and can stop you from deleting a customer who still has orders pointing at them. That guardrail is called referential integrity — it keeps your data from pointing into thin air.

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id)
);

customer_id is a foreign key — each order points back to a real row in customers.

A primary key must be unique; a foreign key has no such rule — many orders can point at the same customer, which is exactly how 'one customer, many orders' works.

Also called
fkreferencerelationship