Question

I've looked at a few SQL posts already but i'm unsure of their answers.. eg: SQL Unique Key Syntax

I want a Cities table... I want to define my country table whereby the Name column is unique... Using this as the base, how do I define a Unique column?

CREATE TABLE [dbo].[Cities]
(
    [CityID] INT NOT NULL PRIMARY KEY, 
    [Name] NCHAR(100) NULL
)
Was it helpful?

Solution 2

You can add the unique keyword:

CREATE TABLE [dbo].[Cities]
(
    [CityID] INT NOT NULL PRIMARY KEY, 
    [Name] NCHAR(100) NULL UNIQUE
);

There are alternative methods. You can add also add a unique index:

create unique index cities_name on dbo.Cities(Name);

Or do it with a unique constraint:

CREATE TABLE [dbo].[Cities]
(
    [CityID] INT NOT NULL PRIMARY KEY, 
    [Name] NCHAR(100) NULL,
    constraint unique_name unique(Name)
);

OTHER TIPS

You can create a constraint on the table to do this:

ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
    <columnname>
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top