Coding⏱️ 2 min read📅 2026-05-31

How to Fix Error 1022 Error – Error 1022 - Can't write; duplicate key in table

Error 1022 occurs when trying to create a table with duplicate primary or unique key constraints.

Quick Answer: Check for existing tables with the same column names and adjust your query accordingly.

The Error 1022 error occurs when you attempt to create a table with duplicate primary or unique key columns. In your case, the issue lies in the `userId` column, which is defined as MEDIUMINT NULL. This allows for null values, and if there are any existing rows with a null value in this column, it can cause a duplicate key error.

🛑 Root Causes of the Error

  • The `userId` column is defined as MEDIUMINT NULL, allowing for null values.

✅ Best Solutions to Fix It

Method 1: Drop and Re-create the Table

  1. Step 1: Drop the existing table using the DROP TABLE command.

Method 2: Update the Table with a Unique Constraint

  1. Step 1: Add a unique constraint to the `userId` column using the ALTER TABLE command.

💡 Conclusion

To avoid this error in the future, ensure that primary or unique key columns do not allow for null values. Additionally, when creating a new table, verify that there are no duplicate keys by using the SHOW CREATE TABLE command.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions