1062
MySQLERRORCommonIntegrity Constraint ViolationHIGH confidence

Duplicate entry for key

What this means

Error 1062 (SQLSTATE 23000) is raised when an INSERT or UPDATE produces a duplicate value in a column protected by a PRIMARY KEY or UNIQUE index. It is the most frequently encountered constraint violation in MariaDB/MySQL applications.

Why it happens
  1. 1Inserting a row with a primary key value that already exists
  2. 2Inserting a row with a duplicate value in a UNIQUE indexed column
  3. 3Updating a row to a value that collides with another existing row's unique column
  4. 4Race condition: two concurrent transactions both checked uniqueness at the application level before either committed
How to reproduce

A duplicate email is inserted into a table with a UNIQUE constraint on email.

trigger — this will error
trigger — this will error
CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  email VARCHAR(255) UNIQUE NOT NULL
);

INSERT INTO users (email) VALUES ('alice@example.com');
INSERT INTO users (email) VALUES ('alice@example.com');  -- triggers 1062

expected output

ERROR 1062 (23000): Duplicate entry 'alice@example.com' for key 'users.email'

Fix 1

Use INSERT IGNORE to silently skip duplicates

WHEN When duplicates should be discarded without error.

Use INSERT IGNORE to silently skip duplicates
INSERT IGNORE INTO users (email) VALUES ('alice@example.com');

Why this works

INSERT IGNORE converts constraint violation errors (including 1062) into warnings, and the duplicate row is discarded. The existing row is left unchanged.

Fix 2

Use INSERT ... ON DUPLICATE KEY UPDATE for upsert

WHEN When a duplicate should update specific columns of the existing row.

Use INSERT ... ON DUPLICATE KEY UPDATE for upsert
INSERT INTO users (email, last_seen)
VALUES ('alice@example.com', NOW())
ON DUPLICATE KEY UPDATE last_seen = VALUES(last_seen);

Why this works

ON DUPLICATE KEY UPDATE detects the constraint conflict and instead executes an UPDATE on the conflicting row using the specified SET expression. Values() refers to the value that would have been inserted.

What not to do

Drop the UNIQUE index to stop the errors

This removes the data integrity guarantee, allowing duplicate business keys to accumulate and creating silent data corruption.

Version notes
MariaDB 10.5+

The error message now includes the schema name in the key reference (e.g., users.email instead of just email) for clearer diagnosis.

Sources

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MySQL errors