Monday, 16 April 2012

What is Unique key in SQL ?

A unique key constraint enforces the uniqueness of the values in a set of columns  so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.
Primary key is also a unique key internally , but cannot allow NULLs , unique key on the other hand allow single NULL , but not multiple nulls over the columns.

Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.


Syntax :


1) unique key while creating a table in SQL Server.


CREATE TABLE Student
(
S_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_StudentID UNIQUE (S_Id,LastName)
)


2) Alter a table :

ALTER TABLE Student
ADD UNIQUE (S_Id)

3) To Drop a Unique constraint:

ALTER TABLE Student
DROP CONSTRAINT uc_StudentID

No comments:

Post a Comment