SQLWarningDatabase ErrorMay 27, 2026

Database Error

ERROR 1217 (42000): Cannot delete or update a parent row: a foreign key constraint fails (`database_name`.`table_name`, CONSTRAINT `fk_table_id` FOREIGN KEY (`id`) REFERENCES `parent_table` (`id`))

What This Error Means

This error occurs when trying to delete or update a row in a table that has a foreign key constraint referencing another table. The row being deleted or updated is still referenced by other rows in the table.

Why It Happens

This error typically happens when a developer tries to delete or update a row that has dependent rows in the same table or in another table. The database will not allow the deletion or update because it would create an inconsistent state in the database.

How to Fix It

  1. 1To fix this error, you need to delete or update the dependent rows first. You can use the `ON DELETE CASCADE` or `ON UPDATE CASCADE` constraint to automatically delete or update dependent rows. Alternatively, you can use a `JOIN` to delete or update the parent row before deleting or updating the dependent row.

Example Code Solution

❌ Before (problematic code)
SQL
DELETE FROM table_name WHERE id = 10;
✅ After (fixed code)
SQL
SET FOREIGN_KEY_CHECKS = 0;
DELETE FROM table_name WHERE id = 10;
SET FOREIGN_KEY_CHECKS = 1;

// Alternatively, use a JOIN to delete the dependent rows first
DELETE t1 FROM table_name t1
INNER JOIN dependent_table t2 ON t1.id = t2.parent_id
WHERE t1.id = 10;

Fix for ERROR 1217 (42000): Cannot delete or update a parent row: a foreign key constraint fails (`database_name`.`table_name`, CONSTRAINT `fk_table_id` FOREIGN KEY (`id`) REFERENCES `parent_table` (`id`))

Related SQL Errors

Related SQL Blog Articles

Have a different error? Get an instant explanation.

Explain Another Error