In this tutorials, we will see the difference between Primary Key and Unique Key.
By default, if you don't specify the UNIQUE constraint, a table column can not hold duplicate values.
Unique key constraint enforces that the column can contains only unique values on which unique constraints is defined. This column can contain multiple null values but all not null values must be unique. Unique Constraint can be defined either at the column level or at the table level.
The following example create a table with constraints for the columns: FirstName when the Employee table is created:
CREATE TABLE Employee (
Eid int NOT NULL,
FirstName varchar(100) UNIQUE,
LastName varchar(100) UNIQUE,
Emailid varchar(100) NOT NULL,
Age int,
Departmentid int
);
The below are the some points which defines primary key:
The following example create a table with constraints for the columns: FirstName when the Employee table is created:
CREATE TABLE Employee (
Eid int PRIMARY KEY IDENTITY(1,1),
FirstName varchar(100) NOT NULL,
LastName varchar(100),
Emailid varchar(100),
Age int,
Departmentid int
);
The IDENTITY property is used for the Eid column to automatically generate unique integer values.
SNo. | Primary Key | Unique Key |
1 | Only one primary key can be present in a table | More than one Unique key can be present in a table |
2 | Primary key cannot be null | Unique keys can contain null |
3 | A table with Primary Key is created as a Clustered Index | A table with Unique Key is created as a Non-Clustered Index |
4 | A Primary key supports auto increment value. | A Unique key does not support auto increment value. |
5 | We cannot change or delete values stored in primary keys. | We can change values stored in Unique keys. |