MySQL PRIMARY KEY Constraint

The PRIMARY KEY constraint is used to set a column to accept unique values.
Difference between UNIQUE and PRIMARY KEY constraint is that, we can have any number of UNIQUE constraint in a table but we can have only one PRIMARY KEY in a table.

Example

   create table employee(empno int PRIMARY KEY, 
   name varchar(50) NOT NULL,
   age numeric, 
   role varchar(50) NOT NULL, 
   location varchar(50) NOT NULL, 
   salary decimal NOT NULL
   );

The above query will set the empno as PRIMARY KEY for the table employee.

DROP PRIMARY KEY

We can drop a primary key of a table using the following table

ALTER TABLE emloyee
DROP PRIMARY KEY;

PRIMARY KEY on ALTER TABLE

We can modify a column to act as PRIMARY KEY with the ALTER TABLE query.

ALTER  TABLE employee
ADD PRIMARY KEY(empno);

Most Read