Primary and Foreign Keys

What is a PK and FK?

A primary key uniquely identifies each row in a table, and a foreign key points to a key in another table. Here is how the two work together in MySQL.

On this page
  1. Primary key: the row’s identifier
  2. Foreign key: the link to another table
  3. Primary key and foreign key side by side
  4. Why the storage engine matters
  5. How the two fit together

Primary key: the row’s identifier

A primary key is a column, or a set of columns, whose values identify each row in a table. The values must be unique, and they can’t be NULL. In MySQL, a table can have only one primary key, though that key can cover more than one column. If the key covers several columns, What is a composite primary key? explains how that works.

Here is a small department table:

CREATE TABLE department (
  department_id INT PRIMARY KEY,
  department_name VARCHAR(100) NOT NULL
) ENGINE=InnoDB;

Each department has one department_id, and no two departments share one.

A foreign key is a column in one table whose values must match a key in another table. The key it points to is usually that table’s primary key. A foreign key column can also hold NULL, which means the row isn’t linked to anything.

Here each employee belongs to a department:

CREATE TABLE employee (
  employee_id INT PRIMARY KEY,
  full_name VARCHAR(100) NOT NULL,
  department_id INT,
  FOREIGN KEY (department_id) REFERENCES department (department_id)
) ENGINE=InnoDB;

With this in place, an employee can’t be linked to a department_id that isn’t in the department table.

Primary key and foreign key side by side

Primary key Foreign key
Where it sits In the table whose rows it identifies In the table that refers to another table
How many per table One As many as the table needs
Can it be NULL? No Yes, unless the column is NOT NULL
Must values be unique in the table? Yes No; many rows can share a value
What it points to Nothing; other tables can point to it A key in another table

Why the storage engine matters

MySQL checks foreign keys in InnoDB, the default storage engine in current releases. The parent and child tables must use the same engine. A table on a different engine doesn’t get these checks, so a value with no match can be stored. For how the engines differ, see types of mysql tables and storage engines.

How the two fit together

A common setup gives each table its own primary key, and a child table a foreign key that points at its parent. A column can also be both at once, as in a one-to-one relationship. That case is covered in Can PK and FK be the same?

The primary key and foreign key rules are separate. A primary key stops two rows in the same table from sharing a value. A foreign key stops a row from pointing at a value that doesn’t exist in the other table.

The complete guide to primary and foreign keys

Can You Have Two Primary Keys in One Table in MySQL?
Read the guide

Keep exploring

Guides from other topics

All topics →