Can't write — duplicate key in table
Production Risk
Medium — write is rejected; application must handle the error.
ER_DUP_KEY (1022, SQLSTATE 23000) is raised when an INSERT or UPDATE violates a unique key constraint. It is a generic form; error 1062 (ER_DUP_ENTRY) provides a more specific message including the duplicate value.
- 1Inserting a row whose key value already exists in the table
- 2Updating a row to a key value that conflicts with an existing row
- 3Bulk load data with duplicate values in a unique column
INSERT INTO t (id) VALUES (1); INSERT INTO t (id) VALUES (1); -- duplicate
expected output
ERROR 1022 (23000): Can't write; duplicate key in table 't'
Fix
Use INSERT IGNORE or ON DUPLICATE KEY UPDATE
WHEN Duplicates are expected and should be silently skipped or merged.
INSERT IGNORE INTO t (id) VALUES (1); -- or: INSERT INTO t (id, val) VALUES (1, 'new') ON DUPLICATE KEY UPDATE val = VALUES(val);
Why this works
INSERT IGNORE discards the duplicate row silently; ON DUPLICATE KEY UPDATE merges the new values into the existing row.
✕ Suppress 1022 without investigating duplicate sources
Silently ignoring duplicates may hide data integrity bugs in the application layer.
MySQL 8.0 — 1022 ER_DUP_KEY
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev