Unique constraint on multiple columns Unique constraint on multiple columns sql-server sql-server

Unique constraint on multiple columns


If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)


By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] (    column [ ASC | DESC ] [ ,...n ])

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](    [userID] [int] IDENTITY(1,1) NOT NULL,    [fcode] [int] NULL,    [scode] [int] NULL,    [dcode] [int] NULL,    [name] [nvarchar](50) NULL,    [address] [nvarchar](50) NULL,    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED     (        [userID] ASC    ),    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED    (        [fcode], [scode], [dcode]    )) ON [PRIMARY]


This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.

  1. Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...

enter image description here

  1. A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button

enter image description here

  1. Check the columns you want included

enter image description here

Click OK in each window and you're done.