SQL Constraints - Unique Key Constraint - DotNet and DataBase

Wednesday, 1 August 2018

SQL Constraints - Unique Key Constraint




The Unique key constraint is to maintain a table column with unique values. Unlike Primary Key, we can add the unique key to more than one column as well unique key allows one null value to be entered in the column.


CREATE TABLE Employees(
    ID int NOT NULL Primary Key,
    LastName varchar(255) NOT NULL UNIQUE,
    FirstName varchar(255),
    Age int
);




Add Unique Key to an existing table  using alter command
ALTER TABLE Employees
ADD UNIQUE (ID);

Add the unique key to more than one column 
ALTER TABLE Employees
ADD CONSTRAINT UC_ Employees UNIQUE (ID,LastName);


Drop Unique Key 
ALTER TABLE Employees
DROP UNIQUE UC_ Employees;

Difference between Unique Key and Primary Key
Primary Key
Unique Key
Primary Key does not allow null values to be inserted
Unique Key allows one null value to be entered into one column
We can't add Primary Key to, more than one column in one table. ()
We can add Unique Key to more than one column under a table.

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.