Oct 21, 2014

UNIQUE KEY constraint in sql server

UNIQUE- This constraint insure that each row for the column has different value.

Example-
Following create a table PRODUCT, column SKU has unique key constraints.

CREATE TABLE PRODUCT
(
ID INT NOT NULL,
SKU VARCHAR(20) NOT NULL UNIQUE,
TITLE VARCHAR(200) NOT NULL,
PRICE MONEY NOT NULL,
DISCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME NULL
)

If table has already been created and we want to apply unique constraints then use following query.

ALTER TABLE PRODUCT
ADD UNIQUE (SKU)

You can also use following syntax, which supports naming the constraint in multiple columns as well

ALTER TABLE PRODUCT

ADD UNIQUE (SKU,ID)