Software⏱️ 3 min read📅 2026-06-03

How to Fix Error 1215 Error – MySQL Error 1215: Cannot add foreign key constraint

MySQL Error 1215: Cannot add foreign key constraint solution.

Quick Answer: Check if the referenced table or column does not exist, and ensure that the referenced column is part of a unique index.

MySQL Error 1215: Cannot add foreign key constraint occurs when you try to create a foreign key constraint on a table that does not have an existing primary key. This error affects database administrators and developers who are trying to enforce data consistency between tables using foreign keys.

This error can be frustrating because it prevents you from enforcing referential integrity, which is crucial for maintaining data consistency in relational databases. Fortunately, there are several ways to resolve this issue, and we will outline the primary fix method and alternative solutions below.

⚠️ Common Causes

  • The primary reason why MySQL Error 1215 occurs is that the table being referenced by the foreign key does not have an existing primary key constraint. In other words, the table does not have a column or set of columns designated as the unique identifier for each row.
  • Another possible cause is that the foreign key itself is not referencing a primary key in another table. This can happen if you are trying to create a foreign key constraint on a non-primary key column or if the referenced table has multiple primary keys.

🔧 Proven Troubleshooting Steps

Enabling InnoDB Engine

  1. Step 1: To resolve the issue, you need to enable the InnoDB storage engine for your database. You can do this by executing the following SQL command: `ALTER DATABASE ENGINE=InnoDB;` Replace `` with the actual name of your database.
  2. Step 2: After enabling InnoDB, try creating the foreign key constraint again. If you still encounter the error, proceed to the next method.

Creating Primary Key on Referenced Table

  1. Step 1: If the referenced table does not have an existing primary key, you need to create one. You can do this by executing the following SQL command: `ALTER TABLE ADD PRIMARY KEY ();` Replace `` and `` with the actual name of the table and column(s) you want to designate as primary key.
  2. Step 2: After creating the primary key, try creating the foreign key constraint again. If you still encounter the error, verify that the referenced column is indeed part of the primary key.

✨ Wrapping Up

To summarize, MySQL Error 1215: Cannot add foreign key constraint occurs when a table does not have an existing primary key or when the foreign key is referencing a non-primary key. By enabling the InnoDB storage engine and creating primary keys on referenced tables, you can resolve this issue and enforce data consistency between tables using foreign keys.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions