MySQLMySQL 1062

MySQL 1062: Duplicate Entry for Key

MySQL 1062 is raised when an INSERT or UPDATE tries to write a value that already exists for a UNIQUE or PRIMARY KEY column. The operation is rolled back to preserve data integrity.

Example Query

INSERT INTO users (id, email) VALUES (1, 'a@example.com');
-- Fails if id=1 already exists

Common Causes

  1. 1Inserting a row with a manually specified primary key that already exists
  2. 2Attempting to set a UNIQUE column to a value present in another row
  3. 3Replaying an idempotent seed script without clearing the table first

How to Fix It

Use INSERT IGNORE or INSERT … ON DUPLICATE KEY UPDATE to handle conflicts gracefully. Let MySQL auto-increment primary keys by omitting the id column. Verify existing data before bulk inserts.

Need a reliable database?

Try Supabase — free PostgreSQL with a generous free tier. No credit card required.

Get started free →

Got a query causing this error?

Paste it into SQLbuddy and get an instant plain-English explanation with optimization tips.

Analyze My Query →