How do you create a unique index on multiple columns?
Posted by KarenKg
Last Updated: July 02, 2024
Creating a unique index on multiple columns ensures that the combination of values in those columns is unique across all rows in a table. This can be particularly useful for enforcing constraints that allow for uniqueness of paired values but not individual ones. Here’s how to create a unique index on multiple columns in various SQL database systems:
In SQL Server:
You can use the following syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, column3);
In MySQL:
You can create a unique index during table creation or by using the ALTER TABLE command. To create during table creation:
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
    UNIQUE INDEX (column1, column2)
);
To add a unique index after the table is created:
ALTER TABLE table_name
ADD UNIQUE INDEX index_name (column1, column2);
In PostgreSQL:
Similar to the previous examples:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, column3);
In SQLite:
You can use the following:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, column3);
Example:
For all of these database systems, here's a practical example. Suppose you have a table called Users and you want to ensure that the combination of first_name and last_name is unique:
CREATE UNIQUE INDEX idx_unique_name
ON Users (first_name, last_name);
Summary:
- Adjust the index and table names appropriately for your database schema. - Ensure that the columns you choose for the unique index do not have any duplicate combinations of values, otherwise, the creation will fail.