MySQL 1210: Key already exists.

When encountering the error 1210: Key already exists in MySQL, the user should:

  1. Identify the specific key or row causing the conflict. Run:


SHOW INDEXES FROM table_name;
Replace `table_name` with the name of the table you're working with. This command shows the indexes and their unique properties.

  1. Check for duplicate entries in the table for the unique key or index identified. For a given unique key `uniquekeyname`, run:


SELECT uniquekeycolumns, COUNT(*)
FROM table_name
GROUP BY unique
keycolumns
HAVING COUNT(*) > 1;

Replace `uniquekeycolumns` with the columns making up the unique key or index, and `table_name` with the actual name of your table.

  1. If duplicates are found, decide on the correct action (e.g., delete duplicates, update to make them unique). To delete duplicates while keeping the first entry, you can use:


DELETE t1 FROM table_name t1
INNER JOIN table_name t2
WHERE
t1.id > t2.id AND
t1.unique
keycolumns = t2.uniquekeycolumns;
Replace `id` with the primary key column and `uniquekeycolumns` with the columns making up the unique key.

  1. If no duplicates are found, or after cleaning up, ensure applications inserting or updating the database handle key uniqueness properly to prevent future occurrences. This might involve checking application logic or constraints.



  1. Finally, if the issue persists, consider checking for hidden characters or case sensitivity issues in the key values, which might cause seemingly unique entries to be considered duplicates. Use `HEX()` function to see if there are hidden characters:


SELECT HEX(column_name), COUNT(*)
FROM table_name
GROUP BY HEX(column_name)
HAVING COUNT(*) > 1;

Replace `column_name` with the name of the column suspected of having hidden characters.

Master

MySQL

in Minutes — Grab the Ultimate Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Real-world configs/examples
Handy troubleshooting shortcuts
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MySQL

Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MORE ISSUES

Made with ❤️ in Bangalore & San Francisco 🏢

Doctor Droid