What is the Difference Between Primary key and Unique key?

🆚 Go to Comparative Table 🆚

The primary key and unique key are both used to ensure the uniqueness of data in a table, but they serve different purposes and have distinct characteristics:

  1. Purpose: The primary key is used to uniquely identify each row in a table and enforce entity integrity, while the unique key is used to prevent duplicate values in a column and enforce unique data.
  2. Existence: A table can have only one primary key, but it can have multiple unique keys.
  3. Nullability: Primary keys cannot accept NULL values, while unique keys can accept multiple NULL values.
  4. Index: A primary key supports a clustered index by default, whereas a unique key supports a non-clustered index.
  5. Modification: You cannot change or delete values stored in primary keys, but you can modify unique key values.

In summary, a primary key is used to identify each row uniquely and enforce entity integrity, while a unique key is used to prevent duplicate values in a column and enforce unique data. A table can have only one primary key, but it can have multiple unique keys. Primary keys cannot accept NULL values, while unique keys can. A primary key supports a clustered index by default, and a unique key supports a non-clustered index. You cannot change or delete values stored in primary keys, but you can modify unique key values[

Comparative Table: Primary key vs Unique key

Here is a table comparing the differences between primary keys and unique keys:

Feature Primary Key Unique Key
NULL values Cannot accept NULL values Can accept NULL values, but only one NULL value is allowed in a table
Number of keys Only one primary key allowed in a table Multiple unique keys allowed in a table
Index Automatically creates a clustered index Generates a non-clustered index
Purpose Enforces entity integrity Enforces uniqueness in a column
Modification Cannot change or delete values stored in primary keys Unique key values can be changed
Usage Identifies each record in the table Prevents duplicate entries in a column

Both primary and unique keys are used to ensure that each row in a table has a unique identifier. However, primary keys do not allow NULL values, while unique keys can accept one NULL value in a column. A table can have only one primary key, but it can have multiple unique keys.