Search code examples
sqlsql-serverprimary-keyunique-constraint

Why can't I specify both a Primary Key and a Unique Constraint on the same table?


I'm trying to create a table:

CREATE TABLE [MyTable]
(
    [Id] [int] IDENTITY,
    [Column1] [int] NOT NULL,
    [Column2] [int] NOT NULL

    CONSTRAINT [PK_MyTable_Id] PRIMARY KEY ([Id])
    CONSTRAINT [UQ_MyTable_Column1_Column2] UNIQUE ([Column1], [Column2])
)

This script fails with the error:

Both a PRIMARY KEY and UNIQUE constraint have been defined for column 'Column2', table 'MyTable'. Only one is allowed.

Why is this restriction enforced? How can I create a table with these properties?


Solution

  • You missed a comma after the primary key constraint.

    CREATE TABLE [MyTable]
    (
        [Id] [int] IDENTITY,
        [Column1] [int] NOT NULL,
        [Column2] [int] NOT NULL
    
        CONSTRAINT [PK_MyTable_Id] PRIMARY KEY ([Id]),
        CONSTRAINT [UQ_MyTable_Column1_Column2] UNIQUE ([Column1], [Column2])
    )