Difference between Primary Key and Unique Key

Shailendra Chauhan  Print 
26 Sep 2012
29 Aug 2018
Intermediate
225K

In SQL Server, we have two keys which distinctively or uniquely identify a record in the database. Both the keys seem identical, but actually, both are different in features and in behaviours. In this article, I would like to share the key differences between primary key and unique key.

For more help about keys in SQL Server refer the article Different Types of SQL Keys.

Difference between Primary Key and Unique Key

Primary Key
Unique Key
Primary Key can't accept null values.
Unique key can accept only one null value.
By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.
By default, Unique key is a unique non-clustered index.
We can have only one Primary key in a table.
We can have more than one unique key in a table.
Primary key can be made foreign key into another table.
In SQL Server, Unique key can be made foreign key into another table.

Defining Primary key and Unique key in SQL Server

 
CREATE TABLE Employee 
 (
 EmpID int PRIMARY KEY, --define primary key
 Name varchar (50) NOT NULL,
 MobileNo int UNIQUE, --define unique key
 Salary int NULL
 ) 
Summary

I hope you will enjoy these tricks while programming with SQL Server. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Hands-on Learning
Free Interview Books
 
+