database error
mysql
duplicate key
error 1022
sql troubleshooting

Error 1022 - Can't write; duplicate key in table

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Error 1022, "Can't write; duplicate key in table," is a common MySQL and MariaDB error that occurs when there is an attempt to create or modify a table in such a way that a duplicate key is encountered. This error often frustrates database administrators and developers who are performing operations involving primary keys, unique keys, or indexes. Understanding why this error occurs and how to resolve it is critical for effective database management.

Understanding Error 1022

When inserting data into a table, MySQL requires that primary keys and unique constraints are respected. These constructs ensure that columns hold unique values, preventing duplication and maintaining data integrity. Error 1022 is triggered when:

  • An insert operation attempts to add a row with a primary key or unique value that already exists in the table.
  • An alter table operation attempts to add or rename indexes that lead to conflicts with existing indexes.

This error message is specific to database operations that involve altering the scheme or modifying index-related attributes of a table.

Common Situations Underscoring Error 1022

  1. Insertion of Duplicate Data
    When inserting data into a table, if a row contains a primary key or unique field that already exists in the table, Error 1022 will arise.
    Example:
    Suppose you have a table `users` with the schema:
  • Error Code: The error code 1022 is closely related to SQL state 23000 ("Integrity constraint violation"), both indicating a failed attempt due to a constraint violation.
  • Storage Engines: Different MySQL storage engines (such as InnoDB and MyISAM) may exhibit varying behaviors in the face of constraint violation errors. Notably, InnoDB supports foreign key constraints, which could also lead to integrity errors similar to 1022 if not managed correctly.
  • Transactional Contexts: In MySQL, if you are using transactional storage engines like InnoDB, failed operations due to Error 1022 can be rolled back without affecting the entire transaction, allowing better error recovery mechanisms.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.