Mysql: ERROR 1215 (HY000): Cannot add foreign key constraint
The ERROR 1215 (HY000) occurs when foreign key and referenced columns are incompatible. Ensuring exact type match, including signedness, and correct composite key referencing can fix the issue. Here's an example to adjust child_column
and match parent_column
's type and attributes:
Aligning data types and attributes
Verify that the InnoDB table engine runs both of your tables that you desire to link with a foreign key:
For an incompatible table engine, an ALTER TABLE operation can convert it to InnoDB:
Understand the importance of indexing
Ensure that your foreign key column is indexed. Indexing not only allows for improved performance, but also promotes optimal data integrity.
Leverage built-in tools for debugging
Say hello to the highly helpful command SHOW ENGINE INNODB STATUS
. Sift through the output focusing primarily on the LATEST FOREIGN KEY ERROR section:
It's essential to cleanse any data discrepancies that contradict new foreign key constraints. A thorough data cleanup might be in order before you add a foreign key.
Always stay unique -- even in foreign key names! A good practice is to name your constraints uniquely across the globe to avoid any clashes and confusion.
Ensuring column and table compatibility
Double-checking can prevent errors. Double-check again to confirm there's no data type mismatch, including considerations for string collations, and unsigned attributes. Here is a command to investigate the exact column specification:
Just as in alphabet song, order matters! Make sure that your SQL script creates tables in a reasonable sequence to prevent foreign-key-to-nowhere scenarios.
Was this article helpful?