Definition
A composite primary key is a primary key made of two or more columns. The combination of values in those columns identifies each row. Two rows can share a value in one of the columns, but they can’t share the full combination. If you searched for two primary key in one table mysql, a composite key is usually the answer.
Syntax
Name all the columns in one PRIMARY KEY clause:
CREATE TABLE enrollment (
student_id INT,
course_id INT,
enrolled_on DATE,
PRIMARY KEY (student_id, course_id)
);
To add a composite key to a table that doesn’t have a primary key yet, use ALTER TABLE enrollment ADD PRIMARY KEY (student_id, course_id);. If the table already has a primary key, this fails, because a table can have only one.
A common mistake is to write PRIMARY KEY after each column:
CREATE TABLE enrollment (
student_id INT PRIMARY KEY,
course_id INT PRIMARY KEY
);
That isn’t a composite key. MySQL returns ERROR 1068 (42000): Multiple primary key defined.
What MySQL does with the columns
- Each column in the key must be
NOT NULL. If you leave that off, MySQL adds it for you, silently. - The uniqueness check applies to the full combination, not to each column on its own.
Here is how the pairs behave:
INSERT INTO enrollment (student_id, course_id, enrolled_on) VALUES (1, 10, '2026-09-01');
INSERT INTO enrollment (student_id, course_id, enrolled_on) VALUES (1, 11, '2026-09-01');
INSERT INTO enrollment (student_id, course_id, enrolled_on) VALUES (1, 10, '2026-10-15');
The first two inserts work, because the pairs (1, 10) and (1, 11) are different. The third fails, because the pair (1, 10) is already in the table.
Why column order matters
MySQL builds the index for the key from the columns in the order you list them. A lookup that filters on the first column, such as student_id = 1, can use that index. A lookup that filters only on the second column usually can’t use it efficiently. So the column order should follow how you query the table.
When a composite key fits
- A junction table, which links two other tables in a many-to-many relationship, such as students and courses.
- A table where the combination of columns is the natural identifier, and no other column is needed to identify a row.
In a junction table, each column of the key is often also a foreign key to one of the two parent tables. Can PK and FK be the same? covers that overlap.
When a single id is simpler
- If many other tables need to point at the row, each foreign key has to list every column of the composite key. A single id is shorter to reference.
- Key values should rarely change. Pick columns that stay stable for the life of the row.