Skip to content
BENIBIX Learn

Foreign Key

Development🗃️ DatabasesDatabase Basics

Also known as FK, Foreign Key Constraint

A column that points to a row in another table. The link is checked for you.

Think of it like

Think of it like a name tag on a lunch box that says whose it is. The tag must match a real pupil.

Example

Each order has a customer_id. When Jack tries to save an order for customer 99, who does not exist, the database says no.

Why it matters

They stop orders that point at customers who are gone.

Definition

A foreign key is a column that points to a row in another table. It holds that row's primary key, so an order can point to its customer. The database checks the link. You cannot point at a row that is not there. It can also stop you from deleting a row that others point to. This is how a relational database ties its tables together.

Example code

sql
INSERT INTO orders (customer_id, total) VALUES (99, 5);
-- Error: FOREIGN KEY constraint failed
There is no customer 99, so the order is refused.

Common mistake

Leaving them out to save time. Broken links then pile up quietly until a report adds up wrong.

Key takeaways

  1. 1
    Points elsewhere. To a primary key in another table.
  2. 2
    Checked for you. No links to rows that do not exist.
  3. 3
    Ties tables together. The heart of a relational database.

Compare