Updated on Kisan Patel
This tutorial will explain you what is the difference between primary key and unique key.
In SQL Server, we have primary and unique keys which uniquely identify a record in database.
Difference between Primary Key & 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 adds a clustered index. | By default Unique key adds a UNIQUE non-clustered index. |
A table can have only one PRIMARY KEY Columns. | A table can have more than one UNIQUE Key Column. |
Below is the example for defining a column as a PRIMARY KEY column while creating a table:
CREATE TABLE dbo.Customer ( Id INT NOT NULL PRIMARY KEY, FirstName VARCHAR(100) )
Below is the example for defining a column as a UNIQUE KEY column while creating a table:
CREATE TABLE dbo.Customer ( Id INT NOT NULL UNIQUE, FirstName VARCHAR(100) )
To set a column as primary key to the existing table in SQL Server:
ALTER TABLE dbo.Customer ( ADD PRIMARY KEY (Id) )
To set a column as unique key to the existing table in SQL Server:
ALTER TABLE dbo.Customer ( ADD UNIQUE (Id) )