1022 🐬 MySQL

MySQL ERROR 1022 (23000): Can't write; duplicate key in table

An ALTER/CREATE produced a duplicate key or constraint name — often a foreign key name that already exists in the database.

Seen on: MySQL

Meaning

Constraint names must be unique per database (not just per table). Copying a table definition reuses FK names.

Common causes

  • Duplicate foreign key constraint name
  • Re-running a migration that adds the same constraint

⚡ Quick fix

  1. Give constraints unique names (fk_orders_user_id)
  2. Check information_schema.TABLE_CONSTRAINTS

Detailed fix by platform

MySQL

  1. SELECT CONSTRAINT_NAME, TABLE_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE();

How to diagnose

  1. Name — Which constraint name collides?
  2. Recent change — Did it start after a deploy, upgrade, or configuration change? Compare with the last working version.

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.