How to Fix Foreign Key Constraint Fails in MySQL
foreign key constraint fails error in MySQL happens when you try to insert or update data that breaks the link between tables. To fix it, ensure the referenced key exists in the parent table and that data types and indexes match between foreign and primary keys.Why This Happens
This error occurs when MySQL cannot enforce the foreign key relationship because the data you are trying to insert or update does not match any existing value in the referenced table. It can also happen if the data types or indexes between the foreign key and referenced key do not match.
CREATE TABLE parent ( id INT PRIMARY KEY ); CREATE TABLE child ( id INT PRIMARY KEY, parent_id INT, FOREIGN KEY (parent_id) REFERENCES parent(id) ); INSERT INTO child (id, parent_id) VALUES (1, 100);
The Fix
To fix this, first insert the referenced key into the parent table before inserting into the child table. Also, ensure the data types and indexes match exactly between the foreign key and the referenced primary key.
INSERT INTO parent (id) VALUES (100); INSERT INTO child (id, parent_id) VALUES (1, 100);
Prevention
Always insert parent table records before child table records to maintain referential integrity. Make sure foreign key and referenced columns have the same data type and character set. Use SHOW CREATE TABLE to verify keys and indexes. Consider using transactions to keep data consistent.
Related Errors
Other common errors include:
- ERROR 1215: Cannot add foreign key constraint, often due to mismatched data types or missing indexes.
- ERROR 150: Foreign key constraint is incorrectly formed, usually from syntax or table engine issues.