Primary key constraint in sql server - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

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

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon