T-SQL Tutorial

Primary key vs Unique key


In SQL Server, both primary keys and unique keys are used to enforce data integrity and ensure the uniqueness of values in a table. However, there are some differences between the two.

A PRIMARY KEY is a column or combination of columns that uniquely identifies each row in a table. It cannot contain null values and must be unique across all rows in the table. By default, SQL Server creates a clustered index on the primary key column(s), which improves performance for queries that use the primary key to retrieve data.

On the other hand, a UNIQUE KEY is also used to enforce uniqueness but does not necessarily identify each row in a table. Unlike a primary key, a unique key can contain null values (with some restrictions). A table can have multiple unique keys, but only one primary key.


Differences

Here are some key differences between primary and unique keys in SQL Server:

1. A primary key is used to identify each row in a table, while a unique key is used to ensure the uniqueness of a column or set of columns.

2. A primary key cannot contain null values, while a unique key can (with some restrictions).

3. A table can have only one primary key, but multiple unique keys.

4. By default, SQL Server creates a clustered index on the primary key column(s), while a unique key creates a non-clustered index.

5. Foreign key relationships are based on primary keys, not unique keys.

In summary, both primary keys and unique keys are used to ensure the uniqueness of data in a table, but primary keys are used to identify each row in the table, while unique keys are used to ensure the uniqueness of a column or set of columns. Understanding the differences between the two is important when designing and implementing a database schema in SQL Server.