When encountering the error 1221: Cannot delete parent row in MySQL DB, it indicates a foreign key constraint is preventing the row deletion due to its reference in a child table. Here are immediate actions to take:
- Run the following query, replacing 'yourtablename' with the name of the table you are trying to delete from:SELECT CONSTRAINT
NAME, TABLE
NAME, COLUMN
NAME, REFERENCED
TABLE
NAME, REFERENCED
COLUMN_NAME
FROM INFORMATIONSCHEMA.KEY
COLUMN_USAGE
WHERE TABLESCHEMA = DatabaseName AND TABLE
NAME = 'your
table
name' AND REFERENCED
TABLE
NAME IS NOT NULL;
This query helps identify the foreign key constraint(s) and the referenced table(s) that are causing the issue.
- Based on the information from step 1, check for dependent rows in the child table. Replace 'childtablename', 'childcolumnname', and 'parent_value' with the relevant table name, column name, and the value you tried to delete, respectively:SELECT * FROM child
table
name WHERE child
column
name = 'parent_value';
- This step helps to understand why the deletion is being blocked.
- Depending on the business logic and necessity, you have a few options:
a. Delete Dependent Rows: If it's safe to remove the dependent rows, you could run:DELETE FROM child
table
name WHERE child
column
name = 'parent_value';
Ensure this does not violate any application logic or data integrity.
b. Update Foreign Keys in Child Rows: If the dependent rows should not be deleted, consider updating them to remove the dependency. This might involve setting the foreign key column to `NULL` or pointing it to a different parent row, if applicable:UPDATE child
table
name SET child
column
name = NULL WHERE child
column
name = 'parent_value';
orUPDATE child
table
name SET child
column
name = 'new
parent
value' WHERE child
column
name = 'parent_value';
c. Temporarily Disable Foreign Key Checks: If you understand the implications and it's absolutely necessary (e.g., bulk cleanup operations), you can temporarily disable foreign key checks:SET FOREIGN
KEY
CHECKS=0;
-- Your DELETE operation here
SET FOREIGNKEY
CHECKS=1;
Be cautious as this can lead to referential integrity issues.
Remember to replace `DatabaseName`, `yourtablename`, `childtablename`, `childcolumnname`, and `parent_value` with actual values relevant to your database and query. Always consider the implications of modifying or deleting data, especially in production environments.
Let Dr. Droid create custom investigation plans for your infrastructure.
Start Free POC (15-min setup) →