In this tutorial, you will learn how to use the SQL Server primary key constraint is used to combine of UNIQUE and Not Null constraints.
The below are the some points which defines primary key:
The following example create a table with constraints for the columns: FirstName when the Employee table is created:
CREATE TABLE Employee (
Eid int PRIMARY KEY IDENTITY(1,1),
FirstName varchar(100) NOT NULL,
LastName varchar(100),
Emailid varchar(100),
Age int,
Departmentid int
);
The IDENTITY property is used for the Eid column to automatically generate unique integer values.
Output
Now insert some data in Employee table.
To assign a particular name to a UNIQUE constraint, you use the CONSTRAINT keyword as follows:
CREATE TABLE Employee (
Eid int,
FirstName varchar(100),
LastName varchar(100) ,
Emailid varchar(100) ,
Age int,
Departmentid int,
PRIMARY KEY(Eid , Departmentid )
);
In this example, the values in either Eid or Departmentid column can be duplicate, but each combination of values from both columns must be unique.
Create table without primary key. The following statement creates a table without a primary key:
CREATE TABLE Employee (
Eid int,
FirstName varchar(100),
LastName varchar(100) ,
Emailid varchar(100) ,
Age int,
Departmentid int
);
To add the PRIMARY KEY constraint to an existing column, create a PRIMARY KEY constraint on the Eid column when the Employee table is already created, use the following SQL Query:
ALTER TABLE Employee
ADD PRIMARY KEY (EID);
Create table without primary key. The following statement creates a table without a primary key:
CREATE TABLE Employee (
Eid int NOT NULL,
FirstName varchar(100),
LastName varchar(100) ,
Emailid varchar(100) ,
Age int,
Departmentid int
);
Now adding primary key on the employee table.
Alter Table employee add constraint pk_Eid primary key(Eid)
Table with primary key looks like:
ALTER TABLE statement is used to drop a primary key in SQL Server.
ALTER TABLE [Employee] DROP CONSTRAINT pk_Eid;
Output
Now table looks like that without primary key