Technology

Primary key constraint in sql server

Introduction: In this article today I am
going to explain Primary key constraint in sql server

Description:

A primary key constraint uniquely identifies each record and
prevents the duplicate values for a column or columns in a database table.
Primary key column can't have null values. Each table can have only one Primary
key and it creates clustered index on the column or columns.

Example to create a table with
primary key constraint:

Createtable Book

(

Id intNOTNULLIDENTITY (1, 1)CONSTRAINT Id PRIMARYKEY(Id),

Book_Name varchar(50),

Book_price int,

Publisher varchar(50)

)

In this example I create a table Book and set Id its
primary key constraint.

Example to alter the table and
create primary key constraint:

Altertable Book

AddCONSTRAINT Id PRIMARYKEY(Id)

Example to delete/drop the
primary key constraint:

Altertable Book

dropCONSTRAINT id

Note: We can use two or more columns
as a primary key, they are called composite key.