Fix "ERROR 1062 (23000): Duplicate entry for key" (MySQL, MariaDB, PostgreSQL)
ERROR 1062 (23000): Duplicate entry '[email protected]' for key 'users.users_email_unique'
- ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
- SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users.users_email_unique'
- Duplicate entry '2147483647' for key 'orders.PRIMARY'
- ERROR: duplicate key value violates unique constraint "users_email_key" DETAIL: Key (email)=([email protected]) already exists.
- SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: users.email
You are inserting or updating a row with a value that already exists in a PRIMARY KEY or UNIQUE column. Find the existing row, then choose: skip the insert, update instead (ON DUPLICATE KEY UPDATE, ON CONFLICT, updateOrCreate) or fix the auto-increment counter.
What this error means
A unique index guarantees that no value (or column combination) appears twice. When an INSERT or UPDATE would create a duplicate, InnoDB cancels it and returns error 1062 with SQLSTATE 23000 (integrity constraint violation). The message gives the conflicting value and the index name; since MySQL 8.0.19 it is prefixed with the table (users.PRIMARY). PostgreSQL reports the same situation with duplicate key value violates unique constraint (SQLSTATE 23505), SQLite with UNIQUE constraint failed.
Common causes
- The value already exists: email already registered, double click on "Submit", retried job, seeder or import run twice.
- Concurrency: the code checks "exists?" then inserts; two simultaneous requests pass the check and the second one fails.
- Case- and accent-insensitive collation: with
utf8mb4_0900_ai_ci,[email protected]and[email protected], oréliseandelise, are considered equal. - Out-of-sync sequence (PostgreSQL): after an import with explicit
idvalues, the sequence hands out anidalready in use. - Auto-increment at its maximum: an
INTkey stuck at2147483647(orTINYINTat127) keeps returning the same value.
Step-by-step fix
-
Identify the index and the existing row
The message gives the value and the index. Show the table definition to see the index columns, then look for the conflicting row.
SHOW CREATE TABLE users; SELECT id, email FROM users WHERE email = '[email protected]'; -
MySQL / MariaDB: update instead of insert
If a duplicate means "update", use
ON DUPLICATE KEY UPDATE. MySQL 8.0.19+ uses a row alias (VALUES()is deprecated there); MariaDB keepsVALUES(). AvoidINSERT IGNORE, which also hides other errors.-- MySQL 8.0.19+ INSERT INTO users (email, name) VALUES ('[email protected]', 'John') AS new ON DUPLICATE KEY UPDATE name = new.name; -- MariaDB INSERT INTO users (email, name) VALUES ('[email protected]', 'John') ON DUPLICATE KEY UPDATE name = VALUES(name); -
PostgreSQL: ON CONFLICT
The same logic in PostgreSQL, naming the constraint column.
DO NOTHINGsimply skips the duplicate.INSERT INTO users (email, name) VALUES ('[email protected]', 'John') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name; -
In the application (Laravel)
updateOrCreatecovers the simple case but is still prone to races.createOrFirst(Laravel 10.29+) relies on the unique index, and the dedicated exception lets you answer the user cleanly.use Illuminate\Database\UniqueConstraintViolationException; $user = User::updateOrCreate(['email' => $email], ['name' => $name]); try { User::create(['email' => $email, 'name' => $name]); } catch (UniqueConstraintViolationException $e) { return back()->withErrors(['email' => 'This email is already registered.']); } -
Resync the sequence or widen the key
PostgreSQL: realign the sequence with the highest
id. MySQL: if the key reached its type’s limit, switch it toBIGINT UNSIGNED(heavy operation on a large table, schedule it).-- PostgreSQL SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT MAX(id) FROM users)); -- MySQL ALTER TABLE orders MODIFY id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT; -
Find duplicates before adding a unique index
If the error happens during a migration that adds
UNIQUE, duplicates already exist. List them, merge or delete them, then rerun the migration.SELECT LOWER(email) AS email, COUNT(*) AS n FROM users GROUP BY LOWER(email) HAVING COUNT(*) > 1;
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Let the database enforce uniqueness (
UNIQUEindex) and handle the exception, rather than relying on "SELECT then INSERT". - Normalize values before writing (
trim, lowercase emails) and disable the submit button after the first click. - Make seeders and imports idempotent with
upsertorON CONFLICT, and useBIGINTkeys for fast-growing tables.
Frequently asked questions
Why "Duplicate entry for key PRIMARY" when the id is auto-increment?
Either you supply the id yourself (import, seeder), or the counter reached the column type’s maximum value. Check with SHOW CREATE TABLE and SELECT MAX(id).
Is INSERT IGNORE a good fix?
Rarely. It skips the duplicate but also turns other errors (truncated values, foreign keys) into mere warnings. Prefer ON DUPLICATE KEY UPDATE or explicit handling.
Why are two different emails treated as duplicates?
The default collation (utf8mb4_0900_ai_ci) ignores case and accents. Use a binary or _as_cs collation on the column if those differences must count.
Useful tools for this error
More Databases (SQL) errors
- Fix "ERROR 1045 (28000): Access denied for user 'root'@'localhost'" (MySQL, MariaDB)
- Fix "Deadlock found when trying to get lock; try restarting transaction" (MySQL, PostgreSQL)
- Fix FATAL: password authentication failed for user "postgres" (PostgreSQL)
- Fix "ERROR 1040: Too many connections" (MySQL) and "too many clients already" (PostgreSQL)
- Fix "ERROR 2006 (HY000): MySQL server has gone away"
- Fix "ERROR 1054 (42S22): Unknown column in 'field list'" (MySQL)
- Fix "ERROR: relation "users" does not exist" (PostgreSQL)