What is Primary Key and how to create in MySQL - MySQL Developer Tutorial

What is Primary key:

Primary Key is constraint can be be created on single or multiple columns, which
identifies each row in table uniquely.


  1. The primary key must have unique value , regardless it is single column or 
  2. combination of values in more than one column.
  3. Primary Key can not have Null value
  4. You will have only single Primary Key per Table in MySQL

Create Primary Key on Single Column in MySQL / MariaDB:

Let's say if we want to create Primary Key on column first name in customer table, we can use below script.

CREATE TABLE `customer` ( `idcustomer` int(11) NOT NULL, `firstname` varchar(50) NOT NULL, `lastname` varchar(30) NULL, `age` int(11) DEFAULT NULL, `phonenumber` char(11) DEFAULT NULL, `dob` date DEFAULT NULL, `gender` char(1) NOT NULL, Constraint pk_firstname Primary Key (firstname) ) ;

Create Primary Key on Multiple columns in MySQL/ MariaDB: 

If we would like to create Primary Key on multiple columns such as first name and last name we can use below script.


CREATE TABLE `customer` ( `idcustomer` int(11) NOT NULL, `firstname` varchar(50) NOT NULL, `lastname` varchar(30) NOT NULL, `age` int(11) DEFAULT NULL, `phonenumber` char(11) DEFAULT NULL, `dob` date DEFAULT NULL, `gender` char(1) NOT NULL, Constraint pk_fname_lname Primary Key (firstname,lastname) ) ;



Create Primary Key on Exiting Table:

In case you need to create the Primary Key on table which is already created. You can use below script in MySQL To add Primary Key. Make sure you don't have duplicate data in the column or columns on which you are going to create the Primary Key, otherwise it will fail if duplicate data exists in the column or columns.
Also the columns should be defined as NOT NULL.

Alter table customer Add Constraint pk_fname Primary Key( firstname);


What is Primary Key in MySQL | How to create Primary Key in MySQL | Drop Primary Key

1 comment: