How can I create a SQL unique constraint based on 2 columns? How can I create a SQL unique constraint based on 2 columns? sql-server sql-server

How can I create a SQL unique constraint based on 2 columns?


You can try this:

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

or

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

or

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


You can add unique constraint tou your fields:

ALTER TABLE YourTableADD CONSTRAINT UQ_UserId_ContactID UNIQUE(UserId, ContactID)


You can try ALTER TABLE [TABLE_NAME] ADD UNIQUE (column1,column2,column3 ...columnN).

Hope this helps cheers.