errorMySQLError 1062

MySQL Error 1062: Duplicate Entry for Key

Error Message
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

1

Use INSERT IGNORE to silently skip duplicate rows: INSERT IGNORE INTO users (email) VALUES ('x@x.com')

2

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)

3

Use REPLACE INTO (deletes conflicting row first, then inserts): REPLACE INTO users (id, email) VALUES (1, 'new@example.com')

4

Pre-check existence: SELECT COUNT(*) FROM users WHERE email = 'x@x.com' (but race conditions are possible)

5

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?
Error 1062 means you tried to insert or update a value that violates a UNIQUE or PRIMARY KEY constraint. For example, if your users table has a unique index on email, inserting a second row with the same email address triggers Error 1062.
How do I insert if not exists in MySQL?
Use INSERT IGNORE: INSERT IGNORE INTO table (col) VALUES (val) — silently skips duplicates. Or INSERT ... ON DUPLICATE KEY UPDATE: INSERT INTO table (col1, col2) VALUES (v1, v2) ON DUPLICATE KEY UPDATE col2 = VALUES(col2) — updates the existing row if a duplicate key is found.
What is the difference between INSERT IGNORE and REPLACE INTO?
INSERT IGNORE silently skips the new row if a duplicate key exists — the existing row is unchanged. REPLACE INTO deletes the existing conflicting row first, then inserts the new row — this changes the auto-increment ID and any columns not specified in the REPLACE.

Related Errors

Still Stuck?

Ask our AI SQL Assistant or the community — get answers in seconds.