Thursday, May 14, 2015

Unique Key in Sql server

Introduction: In this article today I am going to explain Unique Key in Sql server

Description:
Unique Key as name describe only one of its kind means uniquely identifies each record in a database table. It is like a primary key and does not allow the duplicates values in column or columns. The main difference is Unique key allow only one null value and primary key doesn't allow null value. Unique Key by default create a non-clustered index. We can have multiple Unique Keys per table but only have one primary key.

Example:-
Create a table with Unique Key CONSTRAINT:
Create table Book
(
Id int NOT NULL IDENTITY (1, 1) CONSTRAINT Id PRIMARY KEY(Id),
Book_Name varchar(50) UNIQUE,
Book_price int,
Publisher varchar(50)
)

In this example Id is Primary key constraint with auto increment and Book_Name is unique key.

Alter the table and create unique key CONSTRAINT:
Alter table Book
ADD CONSTRAINT  bookname UNIQUE (Book_Name)

Delete/drop the unique key CONSTRAINT:
Alter table Book

Drop CONSTRAINT bookname


No comments:

Post a Comment