How to Add Primary Key?

A primary key is used to uniquely identify each row in a table.
Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the existing table structure (using ALTER TABLE).



CREATE TABLE table_name(field_name datatype(index),…,field_nameN datatype(index),PRIMARY KEY(field_name_primary_key));

Say for example, you are going to create CUSTOMERS TABLE with a declared primary key in your database. Supposed the table has 3 fields present, Customer Name, Customer Address and the contact number. We are going to declare the Customer Name as the primary key for this table. So, we have to follow the given syntax above to do our code.

CREATE TABLE CUSTOMERS(customer_Name varchar(30),Cust_add varchar(50),Cust_Contact_Num int(11),PRIMARY KEY(customer_Name));

To see, the structure of our newly created table we have to describe it. And we got this output:

Another way to create a primary key is by altering the table previously created. We are going to use the syntax below:


ALTER TABLE table_name ADD PRIMARY KEY(field_primary_key);

Say for example, we had created the employees table and we forgot to declare the primary key, then we can use the ALTER command in adding the primary key. Before we start creating primary key by altering the table, let’s describe the employees table first to see its structure.

Then, we are now ready to alter the table using the syntax given above.

ALTER TABLE employees ADD PRIMARY KEY(emp_number);

After the execution of the code, describe the table to see the changes to its structure.

Here it is: