If you have duplicates in the table and you use
ALTER TABLE mytable ADD UNIQUE INDEX myindex (A, B, C, D);
the request will fail with error 1062 (duplicate key).
But if you use IGNORE
ALTER IGNORE TABLE mytable ADD UNIQUE INDEX myindex (A, B, C, D);
duplicates will be deleted. But the documentation does not indicate which line will be saved:
IGNORE is a MySQL extension for standard SQL. It controls how ALTER TABLE works if there are duplicates of unique keys in the new table or if warnings appear when strict mode is enabled. If IGNORE not specified, the copy is canceled and rolled back if errors with duplicate keys occur. If IGNORE specified, only one line is used for rows that duplicates a unique key. The remaining conflicting lines are deleted. Invalid values are truncated to the maximum matching value.
Starting in MySQL 5.7.4, the IGNORE clause for ALTER TABLE is deleted and its use causes an error.
( ALTER TABLE Syntax )
If your version is 5.7.4 or higher, you can:
- Copy the data to a temporary table (this does not have to be a temporary technical).
- Truncate the source table.
- Create a UNIQUE INDEX.
- And copy the data back using
INSERT IGNORE (which is still available).
CREATE TABLE tmp_data SELECT * FROM mytable; TRUNCATE TABLE mytable; ALTER TABLE mytable ADD UNIQUE INDEX myindex (A, B, C, D); INSERT IGNORE INTO mytable SELECT * from tmp_data; DROP TABLE tmp_data;
If you use the IGNORE modifier, errors that occur during execution of the INSERT ignored. For example, without IGNORE , a row that duplicates an existing UNIQUE or PRIMARY KEY index in a table causes an error with a duplicate key, and the statement is aborted. With IGNORE , the string is discarded and no error occurs. Ignored errors generate warnings instead.
(INSERT syntax)
Also see: INSERT ... SELECT Syntax and IGNORE Comparison Keyword and SQL Strong Mode
source share