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:
Create table Book
(
Id int NOT NULL IDENTITY (1, 1) CONSTRAINT Id PRIMARY KEY(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:
Alter table Book
Add CONSTRAINT Id PRIMARY KEY(Id)

Example to delete/drop the primary key constraint:
Alter table Book
drop CONSTRAINT id

Note: We can use two or more columns as a primary key, they are called composite key.
Example of composite key:
Create table Book
(
Id int NOT NULL IDENTITY (1, 1),
Book_Name varchar(50),
Book_price int,
Publisher varchar(50)
CONSTRAINT Id PRIMARY KEY(Id,Book_Name)
)

In this example Id and Book_Name must be unique for the table

Primary key

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget