MySQL Error 1062: Duplicate Entry for Key
ERROR 1062 (23000): Duplicate entry 'john@example.com' for key 'users.email_unique'
What is MySQL Error 1062?
MySQL Error 1062 occurs when an INSERT or UPDATE attempts to add a value that violates a UNIQUE or PRIMARY KEY constraint. The database enforces uniqueness — the same value cannot appear twice in a unique-indexed column.
Common Causes
- 1
Inserting a row with a value that already exists in a UNIQUE indexed column
- 2
Updating a row so its unique column value matches an existing row
- 3
Race condition in concurrent inserts to the same unique column
- 4
Auto-increment sequence reset or manual ID assignment conflicting with existing IDs
- 5
Batch insert containing duplicate values for a unique column
Step-by-Step Solutions
Use INSERT IGNORE to silently skip duplicate rows: INSERT IGNORE INTO users (email) VALUES ('x@x.com')
Use INSERT ... ON DUPLICATE KEY UPDATE to upsert: INSERT INTO users (email, name) VALUES ('x@x.com', 'New Name') ON DUPLICATE KEY UPDATE name = VALUES(name)
Use REPLACE INTO (deletes conflicting row first, then inserts): REPLACE INTO users (id, email) VALUES (1, 'new@example.com')
Pre-check existence: SELECT COUNT(*) FROM users WHERE email = 'x@x.com' (but race conditions are possible)
For ID conflicts: reset auto-increment: ALTER TABLE users AUTO_INCREMENT = (SELECT MAX(id) + 1 FROM users)
Prevention Tips
Use ON DUPLICATE KEY UPDATE for upsert patterns instead of INSERT
Validate uniqueness at the application level before inserting, combined with DB constraint
Use database transactions to prevent race conditions in concurrent inserts
For imported data, deduplicate the source data before batch loading
Frequently Asked Questions
What does MySQL Error 1062 mean?
How do I insert if not exists in MySQL?
What is the difference between INSERT IGNORE and REPLACE INTO?
Related Errors
Still Stuck?
Ask our AI SQL Assistant or the community — get answers in seconds.