Showing posts with label Unique Key. Show all posts
Showing posts with label Unique Key. Show all posts

Friday, 12 May 2017

What is Unique Key?

In this post, I will explain What is Unique Key?

Unique Key provides uniqueness for a column or set of columns in a table like a primary key. It is used to prevent duplicate values in a column. A database table can have more than one Unique Key and it allows at least one NULL value in a column( Nullable). Unique Key generates a Unique Non-Clustered Index

Example of Unique Key-

Create a Unique Key while creating a table

CREATE TABLE tbl_Employee
(
    EmpId INT NOT NULL,
    EmpName VARCHAR(100) NULL,
    CONSTRAINT UC_EmpId UNIQUE (EmpId)
)


Create Unique Key using alter table statement
ALTER TABLE tbl_Employee
ADD CONSTRAINT UC_EmpId UNIQUE (EmpId)

Drop Unique Key using alter table statement

ALTER TABLE tbl_Employee
DROP CONSTRAINT  UC_EmpId

 

Wednesday, 10 May 2017

Difference between Primary Key and Unique Key?

In this post, I will explain the difference between Primary Key and Unique Key.


Primary Key and Unique Key provide uniqueness for a column or set of columns in a table. But there are different characteristics or behaviour of them, which makes Primary Key and Unique Key different. Please find below the difference between Primary Key and Unique Key :


Sr No
Primary Key
Unique Key
1
A database table can have only one Primary Key.
A database table can have more than one Unique Key.
2
Primary Key is not nullable (Doesn't allow NULL value).
Unique Key is nullable (Allows at least one NULL value).
3
Primary Key generates a Unique Clustered Index.
Unique Key generates a Unique Non-Clustered Index.
4
Primary Key is used to identify a row (a record) in a table.
Unique Key is used to prevent duplicate values in a column.