SQL Day 9: Unique Key Constraint

LO1: What is Unique Key Constraint

LO2: When to Use Unique Key

LO3: Difference between Unique Key and Primary Key

Prerequisite: SQL Day 3: Creating Tables & Enforcing Primary and Foreign Key

We use Unique Key to enforce the uniqueness of a column i.e. column should not allow duplicate values.

Creating the Unique Key Graphically

To create the unique key graphically you need to right click on the table and click on Design.



Let say on tblEmployee table we need to make the unique key, to do that right click on column and select Indexes/Keys



In Indexes/Keys pop up click on Add button. After clicking on this button click on ellipsis button and select the Email column



Now set the Is Unique, Type and a proper Name.



Then click on the Close button and Save the table. This will create the Unique Key and will display when you refresh the Keys folder.

Creating the Unique Key using Query

Syntax:

alter table Table_Name
add constraint Unique_Key_Name unique (Column_Name)

Query:

alter table tblEmployee
add constraint UQ_tblEmployee_Email unique (Email)



When we insert the new row with duplicate email then this unique key constraint should be invoked.

Dropping the Unique Key using Graphically

Go to Keys folder, expand it and right click on created unique key and then click on Delete this will delete the created unique key.

Dropping the Unique Key using Query

Syntax:

alter table Table_Name
drop constraint Unique_Key_Name

Query:

alter table tblEmployee
drop constraint UQ_tblEmployee_Email

When to Use Unique Key


A table can have only one primary key. If you want to enforce uniqueness of 2 or more columns, then we use unique key constraint.

Difference between Unique Key and Primary Key

  • A table can have only one Primary key but can have 1 or more unique keys.
  • Primary Key does not allow null values but unique allow only one null

Note: Unique Key only allows one NULL value in complete column i.e. if you try to insert the value as null for the unique key column then only first time (if not already exists NULL) this NULL value successfully inserted and second time when you try to insert the NULL value, unique key constraint will be invoked.


That’s all for today. Thank You.

Comments

Popular posts from this blog

SQL Day 11: Group By in SQL Server

JAVA Script Executor Code to Click on an Element

SQL Day 2: Creating, Altering and Dropping a Database