Incident Response

MySQL ERROR 1062 (23000): Duplicate entry for key 'PRIMARY'

The insert hit a primary key or unique index that already holds the value. Here is how to read the message, the usual causes from explicit IDs to exhausted AUTO_INCREMENT and collation surprises, and which fix is safe on a big production table.

· 15 min read · AG Data Team

ERROR 1062 (23000): Duplicate entry '...' for key 'PRIMARY' means an INSERT or UPDATE tried to write a value that already exists in the primary key or in a unique index. MySQL refuses the row, and in a plain INSERT the whole statement is aborted. The data is fine. The question is why your code tried to write a value that is already there.

mysql> INSERT INTO orders (id, customer_id, total) VALUES (42, 7, 19.90);
ERROR 1062 (23000): Duplicate entry '42' for key 'orders.PRIMARY'

mysql> INSERT INTO users (email) VALUES ('Ana@Example.com');
ERROR 1062 (23000): Duplicate entry 'Ana@Example.com' for key 'users.uq_users_email'

This article is about 1062 on a primary server: in your application, a migration or a data import. If it stopped a replica's SQL thread, read our separate guide on replication error 1062. The cause and the safe fix are different there.

Read the message first

The error reference lists 1062 as ER_DUP_ENTRY with SQLSTATE 23000. The message tells you two things:

Then look at the index and at the row that already holds the value:

-- which index is it, and which columns does it cover?
SHOW CREATE TABLE users\G

-- the row that already holds the value
SELECT id, email, created_at
FROM users
WHERE email = 'Ana@Example.com';

The usual causes

  1. Explicit IDs mixed with AUTO_INCREMENT. Someone imported rows with their own IDs or copied rows from another environment. The InnoDB documentation shows a simple case: a multi-row insert that mixes generated and explicit values fails with a duplicate-key error when an explicit value equals a generated one. Copying a table between servers and then letting both sides generate IDs causes the same problem.
  2. The AUTO_INCREMENT column hit the limit of its type. A signed INT ends at 2147483647 (integer types). The manual says that when the column reaches the upper limit, the next attempt to generate a number fails, and the InnoDB page calls the behaviour past the maximum undefined. In our experience the symptom is 1062 for the maximum value itself, for example Duplicate entry '2147483647' for key 'orders.PRIMARY'. If you see that exact number, stop looking at the application.
  3. Check-then-insert races. The code runs SELECT, sees no row, then runs INSERT. Two requests do this at the same time, and the second one gets 1062. Retries after timeouts and duplicate queue deliveries do the same. The unique index is doing its job, and the code needs a proper upsert.
  4. The collation says two values are equal. In _ci collations, Ana@Example.com and ana@example.com are the same value. In _ai collations, so are e and é (collation suffixes). Older collations such as utf8mb4_unicode_ci are PAD SPACE, which means trailing spaces are ignored in comparisons, while the default utf8mb4_0900_ai_ci is NO PAD (Unicode character sets). Two strings that look different to the application can still collide in the index.
  5. An UPDATE moved a row onto an existing key. UPDATE ... SET sku = 'A-100' fails with 1062 when another row already has that SKU.
  6. A schema change. Adding a unique index to a table that already contains duplicates fails with 1062. The online DDL documentation also warns that, while an online ALTER TABLE applies the log of concurrent changes, it can hit 1062 even when the duplicate was only temporary and later reverted.

Do not "fix" 1062 by removing the unique index. The index is the only thing that stops duplicate orders, double payments or two accounts with one email. Find out why the duplicate was attempted and fix that instead.

Choosing the right fix

MySQL gives you three ways to handle an existing key. They behave very differently.

INSERT ... ON DUPLICATE KEY UPDATE

This is usually the right choice for "insert or update". It updates the existing row in place:

-- insert or update in one statement (row alias syntax, MySQL 8.0.19 and later)
INSERT INTO users (email, name, last_seen)
VALUES ('ana@example.com', 'Ana', NOW()) AS new
ON DUPLICATE KEY UPDATE name = new.name, last_seen = new.last_seen;

-- older servers: the VALUES() form, deprecated in current versions
INSERT INTO users (email, name, last_seen)
VALUES ('ana@example.com', 'Ana', NOW())
ON DUPLICATE KEY UPDATE name = VALUES(name), last_seen = VALUES(last_seen);

The documentation has three details worth knowing. The affected-rows value is 1 for a new row, 2 for an updated row and 0 if the row was set to its current values. Using VALUES() to refer to the new row is deprecated in favour of row aliases. And you should try to avoid this clause on tables with more than one unique index, because if the new row matches different rows through different indexes, only one of them is updated.

INSERT IGNORE

INSERT IGNORE INTO users (email, name) VALUES ('ana@example.com', 'Ana');
SHOW WARNINGS;   -- the duplicate is now a warning, and the row was discarded

IGNORE discards the duplicate row and turns the error into a warning. It also turns other ignorable errors into warnings (INSERT documentation). Use it only when "keep the existing row, drop the new one" is really what you want, and check the warnings. In our experience it is the most common way that bulk loads lose data without anyone noticing.

REPLACE

REPLACE is not an update. According to the REPLACE documentation, when the new row matches an existing one, the old row is deleted before the new one is inserted. Columns you did not specify are reset to their defaults, a new AUTO_INCREMENT value may be generated, and if the table has several unique indexes, one REPLACE can delete several old rows. Avoid it for tables that other tables reference.

What changes on large databases

On a test database a duplicate key is a one-line fix. On large production systems the same error can mean more:

-- how close are AUTO_INCREMENT columns to the limit of their type?
SET SESSION information_schema_stats_expiry = 0;  -- fresh values, not cached ones

SELECT t.table_schema, t.table_name, c.column_name, c.column_type, t.auto_increment,
       ROUND(100 * t.auto_increment /
         CASE
           WHEN c.data_type = 'int'    AND c.column_type LIKE '%unsigned%' THEN 4294967295
           WHEN c.data_type = 'int'                                        THEN 2147483647
           WHEN c.data_type = 'bigint' AND c.column_type LIKE '%unsigned%' THEN 18446744073709551615
           WHEN c.data_type = 'bigint'                                     THEN 9223372036854775807
           WHEN c.data_type = 'mediumint' AND c.column_type LIKE '%unsigned%' THEN 16777215
           WHEN c.data_type = 'mediumint'                                  THEN 8388607
           WHEN c.data_type = 'smallint' AND c.column_type LIKE '%unsigned%' THEN 65535
           WHEN c.data_type = 'smallint'                                   THEN 32767
         END, 1) AS pct_used
FROM information_schema.tables t
JOIN information_schema.columns c
  ON c.table_schema = t.table_schema AND c.table_name = t.table_name
 AND c.extra LIKE '%auto_increment%'
WHERE t.auto_increment IS NOT NULL
ORDER BY pct_used DESC
LIMIT 20;

Key takeaways

MySQL Errors Indexes AUTO_INCREMENT
Work with us

Duplicate key errors in production?

We find the cause of MySQL duplicate key errors, check AUTO_INCREMENT headroom across all tables, and plan INT to BIGINT changes without downtime.

Get in touch More from the blog