Articles → SQL SERVER → Unique Index In SQL Server

Unique Index In SQL Server






Purpose Of Unique Index




  1. Only unique values are allowed
  2. NULL value could be inserted

Syntax


CREATE UNIQUE INDEX index_name ON table_name (column_name)



Example




Picture showing the schema of the sample table




CREATE UNIQUE INDEX idx_unique_SampleTable_Test ON SampleTable (Test)




insert into SampleTable 
values 
  (null) insert into SampleTable 
values 
  ('value1') insert into SampleTable 
values 
  ('value2') insert into SampleTable 
values 
  ('value1')




(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)
Msg 2601, Level 14, State 1, Line 4
Cannot insert duplicate key row in object 'dbo.SampleTable' with unique index 'idx_unique_SampleTable_Test'. The duplicate key value is (value1).
The statement has been terminated.





Posted By  -  Karan Gupta
 
Posted On  -  Sunday, January 1, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250