Skip to main content

UNIQUE KEY constraint in sql server

UNIQUE- This constraint ensures that each row for the column has a 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,
DESCRIPTION VARCHAR(2000)  NULL,
DTCREATE DATETIME NULL
)

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

ALTER TABLE PRODUCT ADD UNIQUE (SKU)

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

ALTER TABLE PRODUCT ADD UNIQUE (SKU, ID)