user2511327
user2511327

Reputation:

how to make two 3 columns are unique in SQL server ?

I want to make three columns are unique in my data table

-----------------------------------
 Column A  |  Column B | Column C
----------------------------------
  Kasun     Cham      Nimith   
----------------------------------
  Kasun     Cham      Rox      - This row ok and must be allowed to add.
----------------------------------
  Kasun     Cham      Nimith  -  but This row must not be allowed to add again, 
---------------------------------

how can I accomplish this in SQL server ?

Upvotes: 8

Views: 4455

Answers (3)

Ahmed
Ahmed

Reputation: 450

To handle that issue with this table design, you need to create a unique constraint on your columns A/B/C.

Upvotes: 0

Kas
Kas

Reputation: 3923

This code will do that what you want.

CREATE UNIQUE CLUSTERED INDEX index_name ON TABLE (col1,col2, col3)
or
CREATE UNIQUE NONCLUSTERED INDEX index_name ON TABLE (col1,col2 , col3)

or

ALTER TABLE [dbo].[TABLE] ADD CONSTRAINT
UNIQUE_Table UNIQUE CLUSTERED
(
col1,
col2, 
col3
) ON [PRIMARY]

Upvotes: 5

jpw
jpw

Reputation: 44881

You can add a unique constraint:

ALTER TABLE [TableName] ADD CONSTRAINT  [constraintName] UNIQUE ([columns])

You can read the documentation here.

Upvotes: 8

Related Questions