Sunday, 27 September 2015

Difference between Primary Key and Unique Key

Below list is major difference between Primary Key and Unique Key Datatype in Sql Server;




Primary Key
Unique Key
Declare Limit
Only one columns can be defined in a table
Table can have more than one Unique Key
Indexing
Primary key  defined as in clustered index
Unique Key defined as unique Clustered index.
Nullable
It not allows the Null value.
It allow null value but only one.
Consist Of
 PRIMARY KEY = UNIQUE KEY + Not Null CONSTRAINT
UNIQUE KEY
Syntax
e.g.  a single column PRIMARY KEY column in table;

Create Syntax for primary Key:

CREATE TABLE dbo.employee
(
EmpId INT NOT NULL PRIMARY KEY,
Name VARCHAR(50),
Address VARCHAR(100),
City VARCHAR(50)
)

Alter Syntax for primary Key:

ALTER TABLE dbo.employee
DROP CONSTRAINT PK_EMPLOYEE
 e.g.  single column UNIQUE KEY column while creating a table

Create Syntax Unique Key;

CREATE TABLE dbo.employee
(
EmpId INT NOT NULL UNIQUE ,
Name VARCHAR(50),
Address VARCHAR(100),
City VARCHAR(50)
)

Alter Syntax Unique Key;

ALTER TABLE dbo.employee
ADD CONSTRAINT UK_EMPLOYEE UNIQUE (EmpId)

No comments:

Post a Comment

Others

You will like to read it