What is difference between Primary, Unique and Composite key ?








Primary Key : ---
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


CREATE TABLE  Employee (
    EmpID int NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Salary       int 
);


Unique  Key :---

The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
Logically, any key which is allowed to contain non duplicate (unique) values is a unique key, NULL is a permissible value in SQL Server , so it can have NULL for a single time just like any other value.

CREATE TABLE  Employee (
    EmpID int NOT NULL ,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Salary       int  ,
     Unique(ID)
);





Composite Key :---


A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.
Sometimes more than one attributes are needed to uniquely identify an entity. A primary key that is made by the combination of more than one attribute is known as a composite key.

 CREATE TABLE TABLE_NAME  
(COLUMN_1, DATA_TYPE_1 NOT NULL,  
COLUMN_2, DATA_TYPE_2   ,  
COLUMN_3, DATA_TYPE_3   NOT NULL,  

Unique (COLUMN_1, COLUMN_3 ));





 


What is difference between Primary, Unique and Composite key ?    What   is difference   between     Primary, Unique and Composite key ? Reviewed by Mukesh Jha on 12:43 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.