MySQL error 1062 (Duplicate Entry) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.
Read the full message: it names the duplicate value and the key ('Duplicate entry X for key Y'). If that does not apply, for idempotent inserts use `INSERT ... ON DUPLICATE KEY UPDATE col=VALUES(col)` or `INSERT IGNORE` — the full checklist is below.
MySQL Error Code: 1062
Official name: Duplicate Entry
Service: MySQL
Duplicate entry '%s' for key %s
INSERT INTO users (email, name)
VALUES ('ada@example.com', 'Ada')
ON DUPLICATE KEY UPDATE
name = VALUES(name);
When the unique key already exists, the UPDATE branch runs instead of failing with 1062.
SELECT email, COUNT(*)
FROM users
GROUP BY email
HAVING COUNT(*) > 1;
Locates existing rows that share a unique value so you can clean them before retrying.
Catch the driver error, check err.code === 'ER_DUP_ENTRY', and map it to HTTP 409 with the duplicate key name.
try {
await pool.query(
'INSERT INTO users (email) VALUES (?) ON DUPLICATE KEY UPDATE email = email',
[email],
)
} catch (err) {
if (err.code === 'ER_DUP_ENTRY') return res.status(409).json({ error: 'Email already taken' })
throw err
}
Let IntegrityError propagate to a handler that inspects the underlying driver code 1062.
from sqlalchemy.exc import IntegrityError
try:
session.add(user)
session.commit()
except IntegrityError as e:
if e.orig.args[0] == 1062:
raise DuplicateUser(email) from e
raise
Check errorInfo[1] === 1062 after catching PDOException and return 409.
try {
$pdo->exec("INSERT INTO users (email) VALUES ('$email')");
} catch (PDOException $e) {
if ($e->errorInfo[1] === 1062) { http_response_code(409); exit('email exists'); }
throw $e;
}
Most often this happens when inserting or updating a row whose value collides with an existing unique key (email, username, order number, external id), or when retrying an insert after a timeout or partial failure, so the row was actually created but the retry hits the unique index.
Read the full message: it names the duplicate value and the key ('Duplicate entry X for key Y').
This page documents fixes for: nodejs-mysql2, python-sqlalchemy, php-pdo.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official MySQL documentation linked below and adds practical troubleshooting guidance on top.