What is a primary key?#

Every table needs a way to find one row exactly and without mistakes. The primary key is that way: a column that is never duplicated across rows and never left empty. Think of a student number at a university; two people may share a name, but their student numbers are never the same.

What makes a good key?#

  • It is unique
  • It is never empty
  • It does not change over time
  • Preferably, it is short

That is why an automatic number (id) is usually created, rather than something like a name or email, which may change.

Example#

In the orders table the id column is the primary key:

idcustomer_idstatus
10017paid
10027pending

Customer number 7 has two orders, but each order has its own number.

Uses#

  • Finding a record quickly
  • Connecting tables through foreign keys
  • Preventing duplicate records

Note#

National ID numbers or emails are usually not used as primary keys, because they may be entered wrongly or change later, and privacy is also a concern. It is better to add a unique column and keep the key separate.