How to add Unique Constraint on multiple columns in SQL Server

You can enforce uniqueness of a column or a combination of the two or more columns using UNIQUE constraints. Creating a unique constraint automatically creates a unique index.

You can define a unique constraint when creating the table (for example on the combination of columns C1, C2 and C3):

CREATE TABLE [dbo].[test](
[ID] [int] IDENTITY(1,1) NOT NULL,
[C1] [int] NULL,
[C2] [int] NULL,
[C3] [int] NULL,
CONSTRAINT [UQ_Constr] UNIQUE
(
[C1], [C2], [C3]
)
)

Or you can add a constraint to an existing table:

ALTER TABLE [dbo].[test]
ADD CONSTRAINT [UQ_Constr] UNIQUE
(
[C1], [C2], [C3]
)

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">