In SQL, the CREATE UNIQUE INDEX statement is used to create a unique index on one or more columns in a table. This ensures that no two rows in the table can have the same values in the indexed columns. It's commonly used to enforce the uniqueness of a column or a combination of columns.
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
index_name: The name you want to assign to the index.table_name: The name of the table where the index is created.column1, column2, ...: The columns that will be included in the index. You can create a unique index on one or more columns.
Example:
CREATE UNIQUE INDEX idx_unique_email
ON users (email);
In this example, a unique index named idx_unique_email is created on the email column in the users table. This will prevent any two rows from having the same email address.
Key Points:
- A unique index helps maintain data integrity by ensuring that values in the indexed columns are unique.
- If you try to insert or update a row with a value that violates the uniqueness constraint, the database will raise an error.
- Unique indexes can be created on one or more columns. When created on multiple columns, it ensures the combination of values in those columns is unique across the table.
Note: In most cases, when you define a column with a UNIQUE constraint, a unique index is automatically created on that column. Using CREATE UNIQUE INDEX explicitly allows more control over the index creation.
No comments:
Post a Comment