Reputation: 21126
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
)
Upvotes: 0
Views: 321
Reputation: 48016
You can create a constraint on the table to do this:
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
Upvotes: 1
Reputation: 1269753
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)
);
Upvotes: 0