You are currently viewing Unique Key Constraint in SQL Server

Unique Key Constraint in SQL Server

Unique Key Constraint in SQL Server

UNIQUE Key constraint is used to enforce the uniqueness of a column. i.e. the column should not allow any duplicate value. UNIQUE Key constraint allows only one NULL value.

The primary key and unique key constraint both are used to enforce the uniqueness of a column, But in the case of a primary key we can create only one primary key in a table, So if there is a need for uniqueness of another column then we can use unique key constraint. 

Primary key constraint does not allow NULL value, while Unique key constraint allows one NULL value. Another NULL value will be considered as the Violation of UNIQUE KEY constraint (cannot inset the duplicate key in the object).

For example, you have an employee table having an email ID column, and as you know two employees do not have the same email ID then we can create a unique key constraint on the email column to enforce the uniqueness of the column.

UNIQUE KEY Constraint on Create Table


ALTER TABLE tblEmployee

This will create a UNIQUE KEY constraint on EmpEmail column, and it will create a name.

But if we want to give name for UNIQUE KEY, then we add the UNIQUE KEY as,

ALTER TABLE tblEmployee
ADD CONSTRAINT UC_tblEmployee UNIQUE (EmpEmail);

This will generate the UNIQUE KEY with the name UC_tblEmployee.

In the above table, you can notice that EmpEmail has a UNIQUE KEY Constraint, Now if we insert some values in this table.

In the below image, I inserted a row in the tblEmployee table, and that succeeded without any issue.

But, When I tried to insert a new row with new EmpID but with the similar EmpEmail, I got Unique Key violation error as below.

DROP a UNIQUE KEY Constraint

ALTER TABLE tblEmployee

Recommended Readings