Showing posts with label Primary Key. Show all posts
Showing posts with label Primary Key. Show all posts

Friday, 12 May 2017

What is Primary Key?

In this post, I will explain What is Primary Key?

Primary Key provides uniqueness for a column or set of columns in a table and used to identify a row (a record) in a table. A database table can have only one Primary Key and a column with a Primary Key doesn't allow NULL value (Not nullable). Primary Key generates a Unique Clustered Index.

Example of Primary Key-

Create Primary Key while creating a table
CREATE TABLE tbl_Employee
(
    EmpId INT NOT NULL,
    EmpName VARCHAR(100) NULL,
    CONSTRAINT PK_EmpId PRIMARY KEY (EmpId)
)

Create Primary Key using alter table statement
ALTER TABLE tbl_Employee
ADD CONSTRAINT PK_EmpId PRIMARY KEY (EmpId)

Drop Primary Key using alter table statement
ALTER TABLE tbl_Employee
DROP CONSTRAINT  PK_EmpId

 

Wednesday, 10 May 2017

Difference between Primary Key and Unique Key?

In this post, I will explain the difference between Primary Key and Unique Key.


Primary Key and Unique Key provide uniqueness for a column or set of columns in a table. But there are different characteristics or behaviour of them, which makes Primary Key and Unique Key different. Please find below the difference between Primary Key and Unique Key :


Sr No
Primary Key
Unique Key
1
A database table can have only one Primary Key.
A database table can have more than one Unique Key.
2
Primary Key is not nullable (Doesn't allow NULL value).
Unique Key is nullable (Allows at least one NULL value).
3
Primary Key generates a Unique Clustered Index.
Unique Key generates a Unique Non-Clustered Index.
4
Primary Key is used to identify a row (a record) in a table.
Unique Key is used to prevent duplicate values in a column.