Skip to content
FR
  1. LuzineDebug
  2. Databases (SQL)
  3. ERROR 1062 (23000): Duplicate entry 'john@exampl…
Databases (SQL) Beginner ≈ 10 min to fix

Fix "ERROR 1062 (23000): Duplicate entry for key" (MySQL, MariaDB, PostgreSQL)

Error message
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
In short

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.

Be the first to confirm this fix

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

  1. The value already exists: email already registered, double click on "Submit", retried job, seeder or import run twice.
  2. Concurrency: the code checks "exists?" then inserts; two simultaneous requests pass the check and the second one fails.
  3. Case- and accent-insensitive collation: with utf8mb4_0900_ai_ci, [email protected] and [email protected], or élise and elise, are considered equal.
  4. Out-of-sync sequence (PostgreSQL): after an import with explicit id values, the sequence hands out an id already in use.
  5. Auto-increment at its maximum: an INT key stuck at 2147483647 (or TINYINT at 127) keeps returning the same value.

Step-by-step fix

  1. 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.

    sql
    SHOW CREATE TABLE users;
    SELECT id, email FROM users WHERE email = '[email protected]';
  2. 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 keeps VALUES(). Avoid INSERT IGNORE, which also hides other errors.

    sql
    -- 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);
  3. PostgreSQL: ON CONFLICT

    The same logic in PostgreSQL, naming the constraint column. DO NOTHING simply skips the duplicate.

    sql
    INSERT INTO users (email, name) VALUES ('[email protected]', 'John')
    ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;
  4. In the application (Laravel)

    updateOrCreate covers 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.

    php
    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.']);
    }
  5. 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 to BIGINT UNSIGNED (heavy operation on a large table, schedule it).

    sql
    -- 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;
  6. 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.

    sql
    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 (UNIQUE index) 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 upsert or ON CONFLICT, and use BIGINT keys 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

All Databases (SQL) errors →