This tutorial explains how to create and drop a primary key in MySQL with syntax and examples.
In MySQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.
You can create a primary key in MySQL with the CREATE TABLE statement.
The syntax to create a primary key using the CREATE TABLE statement in MySQL is:
The name of the table that you wish to create.
The columns that you wish to create in the table. See the MySQL CREATE TABLE statement for more detailed CREATE TABLE syntax as this is an over-simplification to demonstrate how to create a primary Key.
The name of the primary key.
The columns that make up the primary key.
Let's look at an example of how to create a primary key using the CREATE TABLE statement in MySQL.
In this example, we've created a primary key on the contacts table called contacts_pk. It consists of only one column - the contact_id column.
We could also create a primary key with more than one field as in the example below:
This example creates a primary key called contacts_pk that is made up of a combination of the last_name and first_name columns. So each combination of last_name and first_name must be unique in the contacts table.
You can create a primary key in MySQL with the ALTER TABLE statement.
The syntax to create a primary key using the ALTER TABLE statement in MySQL is:
The name of the table to modify.
The name of the primary key.
The columns that make up the primary key.
Let's look at an example of how to create a primary key using the ALTER TABLE statement in MySQL.
In this example, we've created a primary key on the existing contacts table called contacts_pk. It consists of the contact_id column.
We could also create a primary key with more than one field as in the example below:
This example we've created a primary key called contacts_pk that is made up of a combination of the last_name and first_name columns.
You can drop a primary key in MySQL using the ALTER TABLE statement.
The syntax to drop a primary key in MySQL is:
The name of the table to modify.
Let's look at an example of how to drop a primary key using the ALTER TABLE statement in MySQL.
In this example, we've dropped the primary key on the contacts table. We do not need to specify the name of the primary key as there can only be one on a table.