How to Set up Multiple Fields as Primary Key in MySQL
In this tutorial, we are going to see how to set up multiple fields as primary key in MySQL. In MySQL, a primary key is a single field or a combination of fields that uniquely defines a record. None of the fields in the primary key can contain NULL value. In MySQL, a table can have only one primary key.
How to Set up Multiple Fields as Primary Key in MySQL
You can create a primary key in MySQL with the CREATE TABLE statement. The following example creates a table named “Users” and its primary key is composed of the column last_name and first_name:
CREATE TABLE Users ( last_name VARCHAR(20) NOT NULL, first_name VARCHAR(20) NOT NULL, age int, address VARCHAR(100), PRIMARY KEY(last_name, first_name) );
If your table does not have a primary key, you can use the ALTER TABLE statement to add a primary key to a table as shown in the following example:
ALTER TABLE Personnes ADD PRIMARY KEY(last_name, first_name);