HOW TO USE UNIQUE CONSTRAINT IN SQL

UNIQUE in SQL

The UNIQUE constraint in SQL is used to ensure that all values in a column are unique or different.

Example of UNIQUE constraint in SQL server-

CREATE TABLE Students (ID INT NOT NULL UNIQUE, FirstName VARCHAR(200),Fees INT);

Naming of UNIQUE constraint in SQL server during creation of table-

CREATE TABLE Students (ID INT NOT NULL, FirstName VARCHAR(200) NOT NULL, Fees INT , Age INT ,

CONSTRAINT unk UNIQUE (ID, FirstName));  –constraint named as unk

CHECK constraint creation on existing table-

ALTER TABLE Students

ADD UNIQUE (ID);

Naming of UNIQUE constraint in SQL server on existing table-

ALTER TABLE Students

ADD CONSTRAINT unk UNIQUE (ID,FirstName);

DROP a UNIQUE constraint-

ALTER TABLE Students

DROP CONSTRAINT unk;


Leave a Reply

Your email address will not be published. Required fields are marked *