Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly create composite primary keys - MYSQL

People also ask

How do you implement a composite primary key?

When two or more Columns are together Identify the unique row in a table Known as Composite Primary Key. A composite key is a key that is the combination of more than one attribute or column of a given table. It may be a candidate key or a primary key.

How do I add a composite primary key to an existing table in SQL?

You can create an index for composite primary key that uses the same fields present in your composite primary key. mysql> alter table new_orders ADD INDEX new_index (order_id, product_id); Hopefully, now you can create composite primary key in MySQL.

Can a primary key be composite?

Primary keys must contain unique values. A primary key column cannot have NULL values. A table can have only one primary key, which may consist of single or multiple fields. When multiple fields are used as a primary key, they are called a composite key.


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)

Suppose you have already created a table now you can use this query to make composite primary key

alter table employee add primary key(emp_id,emp_name);