Primary and Foreign Keys

Can the same primary key be used in two tables?

A primary key value is unique only inside its own table, so the same value can appear in another table as a foreign key. Here is how shared keys work.

On this page
  1. Short answer
  2. Values repeat across tables, not within one
  3. The same key in both tables
  4. Matching names aren’t a link
  5. Each table still has one primary key

Short answer

Yes. Each table has its own primary key, and the same value can appear in another table. The usual way is a foreign key that points at the first table’s primary key. What a table can’t do is have two primary keys of its own. That is a different question, and searches for two primary key in one table mysql ask about it. MySQL doesn’t allow it.

Values repeat across tables, not within one

Here is a customer table and an orders table:

CREATE TABLE customer (
  customer_id INT PRIMARY KEY,
  customer_name VARCHAR(100) NOT NULL
) ENGINE=InnoDB;

CREATE TABLE customer_order (
  order_id INT PRIMARY KEY,
  customer_id INT NOT NULL,
  order_date DATE,
  FOREIGN KEY (customer_id) REFERENCES customer (customer_id)
) ENGINE=InnoDB;

Customer 42 appears once in customer, because its primary key must be unique there. The same 42 can appear in many rows of customer_order, because a foreign key value can repeat.

The same key in both tables

In a one-to-one design, the second table uses the first table’s key as its own primary key. The same value is then the primary key in both tables, and the second table’s key is also a foreign key. Can PK and FK be the same? explains that overlap in more detail.

Two tables may both have a column named id, or both may have customer_id. The names alone don’t connect them. The link comes from a foreign key constraint, or from the queries that join the tables. Without either, matching numbers are just numbers.

Each table still has one primary key

If the real goal is one table with two identifiers, the answer is different. A composite primary key can cover two columns, and a UNIQUE key can enforce uniqueness on a second column. What is a composite primary key? covers the first option.

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 →