Error Reference › SQL / Database
SQL / Database
Duplicate entry / unique violation (1062)
You tried to insert/update a row that collides with a UNIQUE or PRIMARY key.
What it looks like
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'users.email'
What does "Duplicate entry / unique violation (1062)" mean?
Returned by MySQL when an INSERT or UPDATE would create a second row with the same value in a PRIMARY KEY or UNIQUE column. The message quotes the clashing value and names the index, so you know exactly which rule was hit. PostgreSQL reports the same thing as “duplicate key value violates unique constraint”.
What causes "Duplicate entry / unique violation (1062)"?
- Inserting a value that already exists.
- A race condition creating the same record twice.
- Re-running a seed/import.
How do I confirm the cause?
- Read the key name in the message and look up which column or columns that unique index covers.
- Search the table for the quoted value to see the row that already exists.
- If it happens intermittently, look for two requests creating the same record at once, such as a double-clicked submit button.
How do I fix "Duplicate entry / unique violation (1062)"?
- Check for the existing row first, or use upsert (INSERT … ON DUPLICATE KEY / ON CONFLICT).
- Make the operation idempotent.
- Decide whether the column should really be unique.
How do I stop it happening again?
- Use an upsert (INSERT … ON DUPLICATE KEY UPDATE in MySQL, ON CONFLICT in PostgreSQL) when “create or update” is what you mean.
- Disable submit buttons while a request is in flight, and make imports and seeds safe to run twice.