SQL Topics
Unique Index
title: Unique Index
In previous lessons, you learned about:
- SQL Indexes
- Clustered Indexes
- Non-Clustered Indexes
Indexes help databases retrieve data faster.
However, performance is not the only concern in database design.
Another critical requirement is:
Data IntegrityFor example:
Email Addresses
PAN Numbers
Passport Numbers
Employee Codes
UsernameThese values should be unique.
Imagine a system allowing:
Two Users
Same Email AddressThis could create serious business problems.
To prevent duplicate values while also improving search performance, SQL provides the Unique Index.
A Unique Index ensures that no duplicate values exist in the indexed column while also helping queries execute efficiently.
What is a Unique Index?
A Unique Index is a special type of index that prevents duplicate values from being inserted into a column.
Example:
EmailAllowed:
rahul@gmail.com
priya@gmail.com
amit@gmail.comNot Allowed:
rahul@gmail.com
rahul@gmail.comThe database rejects duplicates automatically.
Why is a Unique Index Important?
Suppose a company stores employee emails.
Table:
EmployeesEmail Column:
rahul@gmail.com
priya@gmail.com
amit@gmail.comNow someone attempts:
rahul@gmail.comagain.
Without a Unique Index:
Duplicate Data StoredWith a Unique Index:
Insert Failsand data integrity is preserved.
How a Unique Index Works
Process:
Insert Value
↓
Check Existing Index Entries
↓
Duplicate Found?
↓
YES → Reject
NO → InsertThe database performs this validation automatically.
Visual Representation
Unique Index:
rahul@gmail.com
priya@gmail.com
amit@gmail.comInsert:
rahul@gmail.comResult:
Duplicate Detected
Insert RejectedCreating Sample Table
CREATE TABLE Employees (
EmployeeID INT,
EmployeeName VARCHAR(100),
Email VARCHAR(100)
);Insert data:
INSERT INTO Employees VALUES
(1,'Rahul','rahul@gmail.com'),
(2,'Priya','priya@gmail.com');Creating a Unique Index
Basic syntax:
CREATE UNIQUE INDEX
IndexName
ON TableName(ColumnName);Example:
CREATE UNIQUE INDEX
IDX_Email
ON Employees(Email);Now:
Duplicate Emails
Not AllowedTesting the Unique Index
Attempt:
INSERT INTO Employees
VALUES
(
3,
'Amit',
'rahul@gmail.com'
);Result:
ERROR
Duplicate Key ViolationThe insertion fails.
Successful Insert
Example:
INSERT INTO Employees
VALUES
(
3,
'Amit',
'amit@gmail.com'
);Result:
Inserted Successfullybecause the email is unique.
Unique Index on Multiple Columns
A Unique Index can be created on multiple columns.
Example:
CREATE UNIQUE INDEX
IDX_NameDepartment
ON Employees
(
EmployeeName,
DepartmentID
);The combination must be unique.
Composite Unique Index Example
Allowed:
| EmployeeName | DepartmentID |
|---|---|
| Rahul | 1 |
| Rahul | 2 |
Different departments.
Not Allowed:
| EmployeeName | DepartmentID |
|---|---|
| Rahul | 1 |
| Rahul | 1 |
Duplicate combination.
Unique Index and NULL Values
Behavior varies between databases.
Some databases allow:
Multiple NULL ValuesOthers allow:
Single NULLAlways verify database-specific behavior.
Unique Index vs Normal Index
Normal Index:
Improves PerformanceUnique Index:
Improves Performance
+
Prevents DuplicatesComparison:
| Feature | Normal Index | Unique Index |
|---|---|---|
| Improves Search Speed | Yes | Yes |
| Prevents Duplicates | No | Yes |
| Data Integrity | No | Yes |
| Storage Required | Yes | Yes |
Unique Index vs PRIMARY KEY
Many developers confuse these concepts.
Primary Key:
Uniqueness Required
NULL Not Allowed
One Per TableUnique Index:
Uniqueness Required
NULL Handling Varies
Multiple AllowedComparison:
| Feature | Primary Key | Unique Index |
|---|---|---|
| Unique Values | Yes | Yes |
| NULL Allowed | No | Depends |
| Number Allowed | One | Multiple |
| Creates Index | Usually Yes | Yes |
Unique Index vs UNIQUE Constraint
Example:
ALTER TABLE Employees
ADD CONSTRAINT UQ_Email
UNIQUE(Email);and:
CREATE UNIQUE INDEX
IDX_Email
ON Employees(Email);Both enforce uniqueness.
However:
UNIQUE Constraint
Focuses On Data Integritywhile:
Unique Index
Focuses On Indexing
And UniquenessReal-World Example: Banking
Columns:
Account Number
PAN Number
Customer IDshould be unique.
Unique indexes prevent duplicates.
Real-World Example: E-Commerce
Columns:
Product SKU
Barcode
Product Codemust remain unique.
Real-World Example: Education System
Columns:
Roll Number
Registration Number
Emailoften require unique indexes.
Real-World Example: HR System
Columns:
Employee Code
Email Address
National IDshould be unique.
Advantages of Unique Index
Prevents Duplicate Data
Major benefit.
Improves Search Performance
Acts like a normal index.
Enhances Data Integrity
Protects business rules.
Supports Fast Lookups
Optimized searches.
Useful for Candidate Keys
Alternative unique identifiers.
Disadvantages of Unique Index
Additional Storage
Indexes require space.
Slower INSERT Operations
Duplicate checking is required.
Slower UPDATE Operations
Index maintenance required.
More Administrative Overhead
Indexes must be managed.
Performance Considerations
Unique indexes improve:
SELECT
JOIN
ORDER BYoperations.
However:
INSERT
UPDATE
DELETErequire additional index maintenance.
Common Errors
Attempting Duplicate Inserts
Most common issue.
Assuming NULL Behavior Is Same Everywhere
Database-specific differences exist.
Creating Unnecessary Unique Indexes
Adds maintenance overhead.
Confusing Unique Index with Primary Key
They are related but different.
Best Practices
Use for Truly Unique Data
Examples:
Email
PAN Number
Passport Number
Employee CodeAvoid Unnecessary Unique Indexes
Only enforce real business requirements.
Understand NULL Handling
Verify database behavior.
Monitor Insert Performance
Large unique indexes may affect write speed.
Document Business Rules
Clarify why uniqueness is required.
Common Interview Questions
What is a Unique Index?
An index that prevents duplicate values while improving query performance.
Can a table have multiple Unique Indexes?
Yes.
Does a Unique Index improve performance?
Yes.
It behaves like a normal index while enforcing uniqueness.
What is the difference between a Primary Key and a Unique Index?
Primary Keys do not allow NULL values and only one exists per table.
Unique Indexes allow multiple definitions and NULL behavior varies.
Why are Unique Indexes important?
They maintain data integrity and prevent duplicate values.
Summary
A Unique Index is a specialized index that combines performance optimization with data integrity enforcement. It ensures unique values, prevents duplicates, supports fast lookups, and is widely used in real-world applications where uniqueness is essential.
In this lesson, you learned:
- What a Unique Index is
- How it works
- Creating Unique Indexes
- Composite Unique Indexes
- NULL behavior
- Unique Index vs Normal Index
- Unique Index vs Primary Key
- Unique Index vs UNIQUE Constraint
- Advantages and disadvantages
- Performance considerations
- Best practices
Mastering Unique Indexes is important because they help maintain accurate, reliable, and high-performance databases.
Next Step
Continue to the next lesson:
Index Performance →
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Unique Index.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, indexing, unique
Related SQL Topics