MySQL error 1062: Duplicate entry for key
A proposed insert or update would duplicate a primary key or unique index value.
ERROR 1062 (23000): Duplicate entry '42' for key 'books.PRIMARY'The message names the conflicting value and key. A key can contain more than one column.
What MySQL error 1062 means
Section titled “What MySQL error 1062 means”MySQL rejected a change that violates uniqueness. Common causes are an existing row, duplicate records in an import, or an edited value that another row already uses.
Concurrent clients can also choose the same key. For text keys, the column’s collation can treat differently spelled values as equal.
Identify the conflict
Section titled “Identify the conflict”These checks apply to local, Docker, and cloud databases alike. Substitute your table and key value in the examples.
-
Read the key name in the error.
-
Inspect its definition:
SHOW CREATE TABLE books; -
Query the row that already uses the value:
SELECT * FROM books WHERE id = 42; -
Correct the proposed change according to your intent.
For a composite key, compare every indexed column. For a new row, supply a different unique value or let MySQL generate its automatic ID. To change an existing record, update that record instead of inserting a second copy.
Preserve the unique constraint when correcting the data. Removing it can allow duplicate records that violate the table’s rules.
Correct an edit or import
Section titled “Correct an edit or import”For a grid edit, inspect the proposed values and SQL using edit data safely. For an import, remove duplicate source keys or correct the destination mapping before retrying; see import and export.
Check the reported transaction outcome first. If the operation includes nontransactional tables, earlier changes can remain after a later statement fails. Use edit rejected or import failures to review the outcome.
Ask a server administrator
Section titled “Ask a server administrator”If the key rule is unclear, provide the database, table, key name, error code, and failure time. Share a redacted message; it can contain private row values. Ask which record should own the unique value.
How TableAI shows it
Section titled “How TableAI shows it”TableAI uses Duplicate Value for this error. The MySQL message identifies the duplicate value and key, so use those details to find the conflict.
Return to the MySQL overview for other MySQL tasks.