How to Fix MySQL Error Code 1215: Cannot Add Foreign Key Constraint
If you are experiencing MySQL Error Code 1215, it means that you are unable to add a foreign key constraint to your table. This error usually occurs due to a mismatch in the data types of the columns or the key columns not being indexed.
Steps to Fix MySQL Error Code 1215
Here are the steps you can follow to fix MySQL Error Code 1215:
- Check the data types of the columns: Make sure that the data types of the columns in both the referencing and referenced tables are the same. If there is a mismatch, you need to make the necessary changes to ensure that the data types match.
- Check if the key columns are indexed: The columns that are used as foreign keys must be indexed. If they are not indexed, you need to create the necessary indexes.
- Check the order of the CREATE TABLE statements: If you are creating the tables in a different order than the order in which they are referenced, you will get this error. Make sure that you create the referenced table first, followed by the referencing table.
- Check for duplicate keys: If there are duplicate keys in the referencing table, you need to remove them before adding the foreign key constraint.
By following these steps, you should be able to fix MySQL Error Code 1215 and add the necessary foreign key constraint to your table.
CREATE TABLE referenced_table (
id INT PRIMARY KEY
CREATE TABLE referencing_table (
FOREIGN KEY (referenced_id) REFERENCES referenced_table(id)
Make sure to use the correct data types and index the necessary columns to avoid this error in the future.