Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a unique index be created in MySQL if the table has repeating values?

Tags:

database

mysql

For an existing table, is it permissible to create a unique on a column that might have repeating values?

like image 226
Leo Romanovsky Avatar asked Apr 24 '13 01:04

Leo Romanovsky


People also ask

Does unique index allow duplicate values?

A unique index never has duplicate values.

Does unique index prevent duplicates?

You can prevent duplicate values in a field in an Access table by creating a unique index.

Can we create unique index when table has duplicate rows Oracle?

By any way, (even by modifying the table definition) can we have unique index on duplicated column??? in below case b1 is the column where there are duplicate rows, but I was asked if I can create a unique index? Answer is simple NO.

Can a table have more than one unique index?

Unlike the PRIMARY KEY index, you can have more than one UNIQUE index per table. Another way to enforce the uniqueness of value in one or more columns is to use the UNIQUE constraint. When you create a UNIQUE constraint, MySQL creates a UNIQUE index behind the scenes.


1 Answers

No, it is not permissible.

The following SQL:

ALTER TABLE `table`
ADD UNIQUE (`column`)

Will generate the following error:

#1062 - Duplicate entry 'data' for key 'column'

You can identify duplicates using:

SELECT * FROM `table`
GROUP BY `column`
HAVING COUNT(`column`) > 1

After removing all of the duplicates, you can add the UNIQUE constraint.

like image 90
Danny Beckett Avatar answered Oct 06 '22 14:10

Danny Beckett