MySQL 1215: Cannot add foreign key constraint.

When encountering error 1215: Cannot add foreign key constraint in MySQL, follow these steps:

  1. Check for Typo in Table or Column Names:


- Ensure the table and column names in the foreign key constraint are spelled correctly.

  1. Verify Table Engine:


- Both tables need to use the InnoDB storage engine. Check with:
SHOW TABLE STATUS WHERE Name = 'yourtablename';

  1. Ensure Matching Column Types:


- The columns you are trying to reference must have the exact same data type and length. Check column types with:
DESCRIBE yourtablename;

  1. Check for Existing Data Violations:


- Ensure that the existing data does not violate the foreign key constraint you are trying to create.

  1. Confirm Foreign Key Columns are Indexed:


- The referenced column(s) in the parent table must be indexed. Check indexes with:
SHOW INDEX FROM yourtablename;

  1. Check for Duplicate Foreign Key Names:


- Ensure that the foreign key name is unique across the database.

  1. Review MySQL Error Log:


- Look into the MySQL error log for any additional messages related to this error.

  1. Try Creating the Foreign Key with a Simplified Syntax:


- Temporarily remove any `ON DELETE` or `ON UPDATE` clauses to isolate the issue.

  1. Check Foreign Key Constraints for the Referenced Table:


- Ensure there are no conflicting constraints on the referenced table that would prevent the addition of the new foreign key.

  1. Execute SHOW ENGINE INNODB STATUS:


- For a detailed explanation of the latest InnoDB foreign key error in the server, run:
SHOW ENGINE INNODB STATUS;
Look under the `LATEST FOREIGN KEY ERROR` section.

Take action based on findings from these steps to resolve the specific cause of the error 1215 in MySQL.

Never debug

MySQL

manually again

Let Dr. Droid create custom investigation plans for your infrastructure.

Start Free POC (15-min setup) →
Automate Debugging for
MySQL
See how Dr. Droid creates investigation plans for your infrastructure.

MORE ISSUES

Made with ❤️ in Bangalore & San Francisco 🏢

Doctor Droid