1062ERRORTier 1 — Safe✅ HIGH confidenceDuplicate 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
- 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
How to reproduce
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 1062Fix 1: Use INSERT IGNORE to silently skip duplicates
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 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.
What not to do
Drop the UNIQUE index to stop the errors
Why it's wrong: 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
📚 Official docs: https://mariadb.com/kb/en/insert-on-duplicate-key-update/
🔧 Source ref: MariaDB Server error code 1062 / ER_DUP_ENTRY
📖 Further reading: MariaDB INSERT ON DUPLICATE KEY UPDATE
Confidence assessment
✅ HIGH confidence
Stable and well-documented. The ON DUPLICATE KEY UPDATE mechanism is consistently available across all supported versions.
See also
🔗 Related errors
📄 Reference pages