Skip to content
BENIBIX Learn

Primary Key vs Foreign Key

A primary key names each row in its own table. A foreign key sits in another table and points back to that name.

Development🗃️ Databases

Primary Key

A column with a different value in each row. That is how one row is found.

A primary key is the column that gives each row in a table its own unique value. No two rows can have the same key, and it can never be empty. It is often a simple number, like id, that the database counts up by itself. Other tables use it to point at a row without confusion. Every table should have one.

Example
Two customers are both called Jack. Their ids are 2 and 7, so the shop never sends the wrong one an order.
Why it matters
Without a unique key, you cannot safely change or delete one row. You might hit two.
Full entry
Development🗃️ Databases

Foreign Key

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

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
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.
Full entry

In one line

Primary Key
A column with a different value in each row. That is how one row is found.
Foreign Key
A column that points to a row in another table. The link is checked for you.