Duplicate entry for key
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.
- 1Inserting a row with a primary key value that already exists
- 2Inserting a row with a duplicate value in a UNIQUE indexed column
- 3Updating a row to a value that collides with another existing row's unique column
- 4Race condition: two concurrent transactions both checked uniqueness at the application level before either committed
A duplicate email is inserted into a table with a UNIQUE constraint on email.
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 1062expected 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.
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.
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.
✕ 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.
The error message now includes the schema name in the key reference (e.g., users.email instead of just email) for clearer diagnosis.
MariaDB Server error code 1062 / ER_DUP_ENTRY
MariaDB INSERT ON DUPLICATE KEY UPDATE ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev