Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete duplicate rows in MySQL table but foreign key relationship exists?

How can I delete duplicate rows from a MySQL table when a foreign key relationship has already been setup up on those rows.
Can the duplicates be merged somehow and then foreign key updated with the new value?

like image 555
chustar Avatar asked Dec 15 '25 20:12

chustar


1 Answers

If the foreign key is ON DELETE CASCADE, then deleting the duplicate rows will also delete the dependent rows, e.g., if you have a table customers and a table orders, and a foreign key like ALTER TABLE orders ADD FOREIGN KEY customer_id REFERENCES customers (id) ON DELETE CASCADE, then deleting a customer will also delete that customer's orders. Similarly, if the foreign key has ON DELETE SET NULL, then the orders will not be deleted, but their customer_id values will be set to NULL.

If neither of these is the desired behaviour, craft a query that resolves the foreign key conflicts by altering the foreign key columns so that they reference the row you want to keep (i.e., update all orders to reference non-duplicate customers), then delete the offending rows.

Yet another alternative is to disable foreign key checks temporarily, but this will leave you with an inconsistent database, so I wouldn't recommend this.

like image 149
tdammers Avatar answered Dec 17 '25 11:12

tdammers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!