How to properly create composite primary keys - MYSQL How to properly create composite primary keys - MYSQL mysql mysql

How to properly create composite primary keys - MYSQL


I would use a composite (multi-column) key.

CREATE TABLE INFO (    t1ID INT,    t2ID INT,    PRIMARY KEY (t1ID, t2ID)) 

This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.


I would not make the primary key of the "info" table a composite of the two values from other tables.

Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?

I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.


the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::

CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

the above example will work if you are writting it while you are creating the table for example ::

CREATE TABLE person (   P_Id int ,   ............,   ............,   CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName));

to add this constraint to an existing table you need to follow the following syntax

ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)