Wednesday, March 11, 2015

Adding unique key constraint

In this post we will try to understand about adding unique key constraint to table in SQL SERVER 2012

Assume you have created a table Users in your database with several columns as per your requirement. And column User_Name should be made unique, i.e. User_Name value should not be repeated.

Note : I am using SQL SERVER 2012 Management Studio.

Now we need to add unique key constraint to our this newly created Users table. In order to achieve this, follow steps below.

  • In Object Explorer, find your database and there your table on which you want to add unique key constraint.
  • Right Click table name to select


Script Table as → Create to → New Query Editor Window.


  • Let us assume the we have to add Unique constraint on column User_Name of our Users table. So write following lines of code in Query Editor Window.



ALTER TABLE [dbo].[User]
ADD CONSTRAINT UNK UNIQUE(User_Name)
 
  • Execute to view that unique key constraint is added successfully.
  • Let's verify by adding same User_Name field twice you will get following error.

 

Unique Key Constraint


In this way we can add Unique key constraint to our table.

No comments:

Post a Comment