MySQL 1169: Duplicate key.

  1. Identify the table and the duplicate key value causing the error by checking the error message details. The error message usually specifies the table and the duplicate key value.



  1. Run the following SQL query to find the duplicate entries in the specified table. Replace `yourtablename` with the actual table name and `yourcolumnname` with the column name that has the duplicate key issue:



SELECT yourcolumnname, COUNT(*)
FROM your
tablename
GROUP BY your
columnname
HAVING COUNT(*) > 1;


  1. Review the rows returned by the query to understand why the duplicates were attempted to be inserted.



  1. If it's safe to remove or modify the duplicate entries, decide whether you need to delete the duplicate or update it to a unique value. Use the following queries to delete or update, but ensure to backup or export critical data before making changes:



- To delete duplicate entries (keep one instance of each duplicate):

DELETE t1 FROM yourtablename t1
INNER JOIN your
tablename t2
WHERE
t1.id > t2.id AND
t1.your
columnname = t2.yourcolumnname;

- To update a duplicate entry to make it unique, replace `newuniquevalue` with the value you want to set, and `id` with the identifier of the row you wish to update:

UPDATE yourtablename
SET your
columnname = 'newuniquevalue'
WHERE id = 'row_identifier';


  1. If necessary, consider adding application-level checks before insertion to ensure duplicates are not being attempted to be inserted into the database.



6. After resolving the duplicate data, attempt the operation that caused the error again to see if it is resolved.

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