Home  >  Article  >  Database  >  Here are a few title options, keeping in mind the question format and the article\'s focus: **Option 1 (Direct & Concise):** How to Remove Duplicates After Creating a Non-Unique Index in MySQL?

Here are a few title options, keeping in mind the question format and the article\'s focus: **Option 1 (Direct & Concise):** How to Remove Duplicates After Creating a Non-Unique Index in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 12:37:02856browse

Here are a few title options, keeping in mind the question format and the article's focus:

**Option 1 (Direct & Concise):** 
How to Remove Duplicates After Creating a Non-Unique Index in MySQL?

**Option 2 (More Specific):**
MySQL Duplicate Rows: How to

Removing Duplicates with Unique Index

In the given scenario, duplicates were inadvertently inserted into a table due to the misconfiguration of an index on columns A, B, C, and D. Despite the aim to prevent duplicates, the index created was a normal index rather than a unique index.

Query Execution

If an attempt is made to alter the existing index from normal to unique or to add a new unique index for the same columns, the query will fail due to the presence of duplicate records.

Alternate Solution with IGNORE Option (Pre-5.7.4)

Using the IGNORE option in the ALTER TABLE syntax allows for the removal of duplicates:

<code class="sql">ALTER IGNORE TABLE mytable ADD UNIQUE INDEX myindex (A, B, C, D);</code>

This will discard duplicate rows, but it's important to note that the documentation does not specify which rows will be kept.

Solution for MySQL 5.7.4 and Above

For versions 5.7.4 and higher, IGNORE is no longer supported in ALTER TABLE. However, the following approach can be used:

  1. Copy the data into a temporary table.
  2. Truncate the original table.
  3. Create a unique index on the table.
  4. Insert the data back into the original table using INSERT IGNORE.

This process will remove duplicates during the INSERT operation.

The above is the detailed content of Here are a few title options, keeping in mind the question format and the article\'s focus: **Option 1 (Direct & Concise):** How to Remove Duplicates After Creating a Non-Unique Index in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn