In this tutorial, we will learn how to use PRIMARY KEY
using SQL.
PRIMARY KEY
Constraint ensures that only unique record is inserted in a table.PRIMARY KEY
is used to uniquely identify each row in a table.PRIMARY KEY
cannot contain NULL
values, it must contains unique values.PRIMARY KEY
, which may consist of single or multiple fields.To add a PRIMARY KEY
constraint when a table is created, a statement is as follow:
CREATE TABLE Employee(
ID int NOT NULL PRIMARY KEY,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int,
Salary decimal(18,2)
);
CREATE TABLE Employee(
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int,
Salary decimal(18,2),
PRIMARY KEY (ID)
);
To define a PRIMARY KEY
constraint on multiple columns, a statement is as follow:
CREATE TABLE Employee (
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255),
Age int,
Salary decimal(18,2),
CONSTRAINT PK_Employee UNIQUE (ID,EmpName)
);
To add a PRIMARY KEY
constraint after creating a table, a statement is as follow:
ALTER TABLE Employee
ADD PRIMARY KEY(ID);
To add a PRIMARY KEY
constraint after creating a table on multiple columns, a statement is as follow:
ALTER TABLE Employee
ADD CONSTRAINT PK_Employee UNIQUE (ID,EmpName);
To drop a PRIMARY KEY
Constraint, the statement is as follow:
ALTER TABLE tableName
DROP CONSTRAINT PK_constraintName;
ALTER TABLE Employee
DROP CONSTRAINT PK_Employee;
ALTER TABLE Employee
DROP PRIMARY KEY;