MySQL ERROR 1062 (23000): Duplicate entry for key
An INSERT/UPDATE would create a duplicate value in a PRIMARY or UNIQUE key.
Meaning
The message names the duplicate value and the index (e.g. Duplicate entry 'a@b.com' for key 'users.email_unique'). Your data violates a uniqueness rule — or AUTO_INCREMENT is out of sync after an import.
Common causes
- Inserting a record that already exists (double submit, retry)
- Unique column like email/username already taken
- AUTO_INCREMENT counter lower than existing max id after manual import
- Race condition between check-then-insert
⚡ Quick fix
- Check for the existing row by the named key
- Use
INSERT … ON DUPLICATE KEY UPDATEorINSERT IGNOREdeliberately - Fix AUTO_INCREMENT:
ALTER TABLE t AUTO_INCREMENT = <max+1>; - Catch the error and show “already exists” to users
Detailed fix by platform
MySQL
- Upsert:sql
INSERT INTO users (email, name) VALUES ('a@b.com', 'Asha') ON DUPLICATE KEY UPDATE name = VALUES(name);
PHP
- Catch
PDOExceptionwith SQLSTATE 23000 / driver code 1062 and return a 409 or friendly validation error.
How to diagnose
- Key — Which index and value?
- Existing row — Who inserted it?
- Auto increment — In sync with max(id)?
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026