1062 🐬 MySQL

MySQL ERROR 1062 (23000): Duplicate entry for key

An INSERT/UPDATE would create a duplicate value in a PRIMARY or UNIQUE key.

Seen on: MySQL PHP

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

  1. Check for the existing row by the named key
  2. Use INSERT … ON DUPLICATE KEY UPDATE or INSERT IGNORE deliberately
  3. Fix AUTO_INCREMENT: ALTER TABLE t AUTO_INCREMENT = <max+1>;
  4. Catch the error and show “already exists” to users

Detailed fix by platform

MySQL

  1. Upsert:
    sql
    INSERT INTO users (email, name) VALUES ('a@b.com', 'Asha')
    ON DUPLICATE KEY UPDATE name = VALUES(name);

PHP

  1. Catch PDOException with SQLSTATE 23000 / driver code 1062 and return a 409 or friendly validation error.

How to diagnose

  1. Key — Which index and value?
  2. Existing row — Who inserted it?
  3. 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.