Unique Key in RDBMS

A Unique Key is a constraint in RDBMS that ensures all values in a column (or set of columns) are distinct. Many users confuse Primary Key with Unique Key since both enforce uniqueness, but they differ in NULL handling, volume, and modifiability.

The unique key constraint is essential for maintaining data integrity by preventing duplicate entries while providing more flexibility than primary keys. It's commonly used for columns like email addresses, phone numbers, or social security numbers where uniqueness is required but the field may not serve as the primary identifier.

Primary Key vs Unique Key

Feature Primary Key Unique Key
Purpose Provides uniqueness and identifies each row Prevents duplicate values in a column
NULL Values Cannot accept NULL Allows one NULL value
Count Per Table Only one per table Multiple allowed per table
Modification Cannot be modified Can be modified
Index Created Clustered index Non-clustered index

Visual Representation

The following diagram illustrates the concept of unique key constraints in a database table ?

Employee Table EmpID (PK) EmpName Email (UNIQUE) 1 Alice alice@company.com 2 Bob NULL Primary Key: No duplicates, No NULL | Unique Key: No duplicates, One NULL allowed

Example

In the following Employee table, EmpID is the primary key and EmpEmail has a unique key constraint ?

EmpID (PK) EmpName EmpEmail (UNIQUE)
1 Alice alice@company.com
2 Bob bob@company.com
3 Charlie NULL

EmpID cannot be NULL or duplicated (primary key). EmpEmail cannot be duplicated but allows one NULL value (unique key).

SQL Example

The following SQL creates a table with both primary key and unique key constraints ?

CREATE TABLE Employee (
    EmpID INT PRIMARY KEY,
    EmpName VARCHAR(50),
    EmpEmail VARCHAR(100) UNIQUE
);

-- Valid: unique email
INSERT INTO Employee VALUES (1, 'Alice', 'alice@company.com');

-- Valid: NULL is allowed for unique key
INSERT INTO Employee VALUES (2, 'Bob', NULL);

-- Invalid: duplicate email (violates unique constraint)
-- INSERT INTO Employee VALUES (3, 'Charlie', 'alice@company.com');

-- Display the table
SELECT * FROM Employee;

The output of the above code is ?

EmpID | EmpName | EmpEmail
------|---------|------------------
1     | Alice   | alice@company.com
2     | Bob     | NULL

Conclusion

A Unique Key prevents duplicate values in a column while allowing one NULL. Unlike a Primary Key (which is limited to one per table and cannot be NULL), a table can have multiple Unique Key constraints to enforce uniqueness on different columns.

Updated on: 2026-03-14T20:40:10+05:30

948 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements