MySQL 1216: Cannot delete or update a parent row.

When encountering error 1216: "Cannot delete or update a parent row" in MySQL, it indicates a foreign key constraint failure. Here are immediate actions to investigate and address the issue:

  1. Identify the Foreign Key Constraint:


- Run the following query to identify the foreign key constraint that is causing the issue. Replace `yourtablename` with the name of the table you are trying to update or delete from.
SELECT CONSTRAINTNAME, TABLENAME, COLUMNNAME, REFERENCEDTABLENAME, REFERENCEDCOLUMN_NAME
FROM INFORMATION
SCHEMA.KEYCOLUMN_USAGE
WHERE TABLE
SCHEMA = 'yourdatabasename' AND TABLENAME = 'yourtablename';

  1. Check for Dependent Rows in the Child Table:


- Use the information obtained from step 1 to find dependent rows in the child table. Replace `childtablename`, `childcolumnname`, `parenttablename`, and `parentcolumnvalue` with the actual table and column names, and the value you tried to delete or update.
SELECT * FROM childtablename WHERE childcolumnname IN (SELECT parentcolumnvalue FROM parenttablename WHERE your_condition);

  1. Decide on Action for Dependent Rows:


- Based on the business logic, decide if you need to delete, update, or reassign these dependent rows. Here are examples for each action:

Delete Dependent Rows (Caution: This will permanently remove the dependent rows):
DELETE FROM childtablename WHERE childcolumnname = 'value';

Update Dependent Rows (To remove the dependency before deleting/updating the parent row):
UPDATE childtablename SET childcolumnname = 'newvalue' WHERE childcolumnname = 'oldvalue';

Reassign Dependent Rows (To another parent row, if applicable):
UPDATE childtablename SET childcolumnname = 'newparentvalue' WHERE childcolumnname = 'currentparentvalue';

  1. Retry the Original Operation:


- After addressing the dependent rows, retry the original delete or update operation on the parent table.

Ensure that each action taken is in line with your application's data integrity and business rules.

Master

MySQL

in Minutes — Grab the Ultimate Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Real-world configs/examples
Handy troubleshooting shortcuts
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MySQL

Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MORE ISSUES

Made with ❤️ in Bangalore & San Francisco 🏢

Doctor Droid