SQL CREATE UNIQUE INDEX Statement
The CREATE UNIQUE INDEX
statement in SQL creates a unique index on a table. A unique index ensures that all values in the indexed column(s) are unique, preventing duplicate entries. This is crucial for maintaining data integrity.
CREATE UNIQUE INDEX: Definition and Usage
Unique indexes dramatically speed up data retrieval, especially when searching or filtering based on the indexed column(s). They work like a highly efficient lookup table. However, adding a unique index increases the time it takes to add or update data because the database must check for uniqueness before each insertion or modification.
Syntax
Syntax
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Remember that the syntax for creating indexes can vary slightly depending on your database system (e.g., MySQL, PostgreSQL, SQL Server). Always consult your database's documentation for the precise syntax.
Important Note on Index Updates
Adding indexes improves query speeds but slows down table updates (inserts, updates, and deletes). Only create indexes on columns frequently used in WHERE
clauses to maximize performance benefits.
Example
Creating a Unique Index
This example creates a unique index named 'uidx_pid' on the 'PersonID' column of the 'Persons' table. This ensures that all values in the 'PersonID' column are unique.
Syntax
CREATE UNIQUE INDEX uidx_pid
ON Persons (PersonID);
Output
A unique index named 'uidx_pid' is created on the 'PersonID' column of the 'Persons' table. Attempts to insert duplicate 'PersonID' values will result in an error.