CREATE UNIQUE INDEX builds a physical index structure on one or more columns and simultaneously enforces a uniqueness constraint. During creation, the database scans existing data and aborts if duplicate combinations are found. After creation, any INSERT or UPDATE that would duplicate an indexed key fails with an error. Because the index is unique, the optimizer can use it for fast look-ups and to eliminate duplicates in query plans. Some systems automatically create a unique index when you declare a PRIMARY KEY or UNIQUE constraint; CREATE UNIQUE INDEX is the manual, fully-qualified form that offers finer control over index name, included columns, sort order, storage parameters, and, in some dialects, filtered conditions or tablespaces. Be aware that uniqueness rules usually treat NULL as a distinct value per row in PostgreSQL, Oracle, and SQLite, but treat multiple NULLs as duplicates in SQL Server unless otherwise configured.
index_name
(identifier) - Name of the index to create.table_name
(identifier) - Table that owns the index.column_list
(identifiers) - One or more columns whose combined values must be unique.ASC
(DESC) - keyword|||Optional sort direction per column.INCLUDE
(keyword) - Extra columns stored in index but not part of key (not all dialects).WHERE predicate
(expression) - Optional filter for a partial/filtered unique index.WITH
(...) - clause – Storage parameters such as fillfactor or tablespace.CREATE INDEX, UNIQUE constraint, PRIMARY KEY, DROP INDEX, ALTER INDEX, CLUSTERED INDEX
SQL-92 (formalized); available earlier in vendor implementations such as Oracle 7 and PostgreSQL 6
The command aborts with an error and no index is created. Remove or update duplicate rows, then rerun CREATE UNIQUE INDEX.
Speed is identical because both create the same underlying structure. Use CREATE UNIQUE INDEX when you need extra options like INCLUDE or WHERE.
Cast or extract the JSON value to a deterministic type in the index expression, for example:CREATE UNIQUE INDEX ux_contacts_email ON contacts ((email_json->>'address'));
Most dialects do not allow ALTER INDEX to change uniqueness. Drop the old index and recreate it as UNIQUE.