Search code examples
mysqlindexingunique-index

Unique Index Fail


I created a unique index for employee IDs to an existing table. I did a test and entered an employee ID already saved in the database, and the database still saved it. When I do a search on that ID it lists both records.

Test the index by inserting a record with a duplicate employee ID

CREATE INDEX empid_index ON staff (empId)

Expected an error message of a duplicated ID, but no error came up, the record was still saved.


Solution

  • Don't create unique indexes: add unique constraints to the table instead. For example:

    create table staff (
      ...
      constraint unique_empid unique (empid),
      ...
    );
    

    Even though unique indexes will prevent you from inserting duplicate rows with that value, you will be missing other features of the constraint, such as exporting foreign keys, that you may need later on.