Open In App

Unique Constraint in MS SQL Server

Last Updated : 20 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

A table might have repetitive data in form of rows. This might cause glitches while retrieving data from the query. To avoid them, a unique constraint is used. Unique allows sorting a column or set of columns uniquely meaning, a user cannot insert a duplicate or repeated value in a column as it results in an error. A unique constraint is enforced in a table while creating a table.

Example –
If a user wants to create a Student table and wants to enforce unique constraint, it can be done as follows –

create table Student
(name varchar2(30), rollnumber int unique, age int)

Table – Student

Name Rollnumber Age
Aisha 111 CSE
Piya 112 Mech

In the table created above, rollnumber is enforced a unique constraint as each student is assigned different rollnumber to avoid confusions. For further understanding, an example is given below –

insert into student 
values ('Maya', '111', 'CSE');

Output :
It results in an error as 111 is already assigned to another student. This way unique constraint restricts the use of duplicates in a table.

Result :
Violation of UNIQUE KEY constraint ‘UQ__Student__EBE41F7A3D93XXXX’. Cannot insert duplicate key in object ‘Student’.
The duplicate key value is (111).
The statement has been terminated.

Note –
The primary key and Unique has the same functionality of enforcing uniqueness among a set of columns to avoid repetitions. The only difference between primary key and unique is that the primary key can be used only once while unique can be used more than once.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads