Primary and Foreign Keys

Can PK and FK be the same?

A column can be both a primary key and a foreign key, and this is common in one-to-one and junction tables. Here is when it works and when it does not.

On this page
  1. Short answer
  2. A shared primary key for one-to-one
  3. A junction table
  4. Limits that still apply
  5. When to use a separate key

Short answer

Yes. One column can be a primary key and a foreign key in the same table. The database applies both rules to that column: its values must be unique and can’t be NULL, and each value must match a row in the other table. If the terms are new, What is a PK and FK? defines both.

A shared primary key for one-to-one

In a one-to-one relationship, each row in one table has at most one matching row in another. A common way to model this is to let the child table use the parent’s key as its own primary key:

CREATE TABLE user_account (
  user_id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE user_profile (
  user_id INT PRIMARY KEY,
  bio TEXT,
  FOREIGN KEY (user_id) REFERENCES user_account (user_id)
) ENGINE=InnoDB;

user_profile.user_id is the primary key, so each account can have only one profile row. It’s also a foreign key, so a profile can’t exist without its account.

A junction table

A junction table links two other tables in a many-to-many relationship. Its composite key often uses the same columns as its foreign keys:

CREATE TABLE enrollment (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES student (student_id),
  FOREIGN KEY (course_id) REFERENCES course (course_id)
) ENGINE=InnoDB;

Here student_id and course_id are both part of the primary key and foreign keys. The example assumes student and course tables exist, each with its own primary key.

Limits that still apply

  • The primary key rules still apply. Values are unique within the table, and they can’t be NULL.
  • The foreign key rules still apply. Each value must exist in the parent table.

When to use a separate key

If one parent row can have many child rows, the child table needs its own primary key. The link to the parent then goes in a separate foreign key column. Sharing the parent’s key would allow only one child per parent. If you’re not sure which design fits, a separate key is the safer choice.

Whether the same key value can appear in two tables is a related question, covered in Can the same primary key be used in two tables?

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 →