Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
Benjamin Hodgson Avatar asked Apr 11 '14 12:04

Benjamin Hodgson


People also ask

Can a table have both primary key and unique key?

A table can have only one primary key whereas there can be multiple unique key on a table.

Can unique constraint be used on primary key?

PRIMARY KEY constraint differs from the UNIQUE constraint in that; you can create multiple UNIQUE constraints in a table, with the ability to define only one SQL PRIMARY KEY per each table. Another difference is that the UNIQUE constraint allows for one NULL value, but the PRIMARY KEY does not allow NULL values.

Can a column be a primary and unique key?

You can define multiple unique keys in one table, as there may be multiple columns that store only unique values. A primary key and a unique key can both be present in a table (as shown in some of the examples); however, it makes no sense to define both a unique key and a primary key on the same column(s).

Can a row be both primary and foreign key?

Yes, it can.


Video Answer


2 Answers

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])
)
like image 91
CynicalSection Avatar answered Sep 19 '22 15:09

CynicalSection


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

    CONSTRAINT [PK_MyTable_Id] PRIMARY KEY ([Id])

)

  ALTER TABLE [MyTable] ADD CONSTRAINT [UQ_MyTable_Column1_Column2] UNIQUE ([Column1], [Column2])
like image 43
mohan111 Avatar answered Sep 21 '22 15:09

mohan111