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:
- The value in quotes. For a composite key, the column values are joined with a dash, for example
'7-2026-11-24'. - The key name. Since MySQL 8.0.19, the key name includes the table name, as in
'orders.PRIMARY'. Older servers show only'PRIMARY', which is less helpful when one statement touches several tables. If the key is notPRIMARY, it is a secondary unique index, and that changes the diagnosis completely.
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
- 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.
- The AUTO_INCREMENT column hit the limit of its type. A signed
INTends 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 exampleDuplicate entry '2147483647' for key 'orders.PRIMARY'. If you see that exact number, stop looking at the application. - Check-then-insert races. The code runs
SELECT, sees no row, then runsINSERT. 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. - The collation says two values are equal. In
_cicollations,Ana@Example.comandana@example.comare the same value. In_aicollations, so areeandé(collation suffixes). Older collations such asutf8mb4_unicode_ciarePAD SPACE, which means trailing spaces are ignored in comparisons, while the defaultutf8mb4_0900_ai_ciisNO PAD(Unicode character sets). Two strings that look different to the application can still collide in the index. - An UPDATE moved a row onto an existing key.
UPDATE ... SET sku = 'A-100'fails with 1062 when another row already has that SKU. - 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 TABLEapplies 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:
- Running out of AUTO_INCREMENT values is an outage, not a bug. When an
INTkey is exhausted, every insert that needs a new ID fails. Check headroom regularly across all tables with the query below.information_schema.tables.auto_incrementis cached forinformation_schema_stats_expiryseconds, 86400 by default (system variables), so set it to 0 in the session first.
-- 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;
- Changing INT to BIGINT is a full table copy. The online DDL table shows that changing a column data type only supports
ALGORITHM=COPYand does not permit concurrent DML. On a table with hundreds of millions of rows, plan it months ahead and use an online schema change tool, as described in our guide to ALTER TABLE without downtime. Foreign key columns in other tables must change too. - IDs are used faster than the row count suggests. InnoDB does not reuse values from rolled-back inserts, and with the default interleaved lock mode (
innodb_autoinc_lock_mode=2) bulk inserts can leave gaps (auto-increment handling). A table with 500 million rows can be much closer to the limit than you think. Look at the counter, not atCOUNT(*). - Several writers, one key space. If two servers accept writes for the same table, their generated IDs collide unless you separate them, for example with
auto_increment_incrementandauto_increment_offset, which the documentation describes for source-to-source replication. Merging data from shards or tenants into one table needs the same planning. - Measure, do not just catch. In our experience, a steady trickle of 1062 from one endpoint points to a check-then-insert race or duplicate message delivery, while a sudden wall of 1062 on one table points to an exhausted key or a bad import. Count 1062 per table and per application in your logs, and alert on sudden changes.
- Unique index changes on big tables need a duplicate check first. Run the
GROUP BY ... HAVING COUNT(*) > 1query on a replica, clean the data in batches, then add the index with an online method. Otherwise theALTERcan run for hours and fail at the end.
Key takeaways
- 1062 means the value is already in a primary key or unique index. Read the value and the key name in the message first.
Duplicate entry '2147483647'on a signedINTkey means the AUTO_INCREMENT range is exhausted, not an application bug.- Collations decide equality: case, accents and, in
PAD SPACEcollations, trailing spaces. - Prefer
ON DUPLICATE KEY UPDATE. UseINSERT IGNOREonly with warnings checked, and avoidREPLACEon referenced tables. - At scale: monitor AUTO_INCREMENT headroom, plan BIGINT changes early and count 1062 per table.