I have two tables (Parent and Child) containing millions of records. I want to delete some rows (106 rows) from both tables. Which is the best approach to do this? I have dropped a foreign key constraint before deleting rows from Parent. But when I try to add the constraint, it is taking 10 minutes to execute. Could you suggest some other better approach?
The reason it takes so long to add the constraint back is because the database has to check each Child to ensure that the foreign key is valid, and that could be millions of checks.
In my opinion, the best way to do this is with ON DELETE CASCADE. You won't need to drop the foreign key constraint, or add it back afterwards. In fact, it is this constraint which makes the synchronized deletion from both tables possible.
This was first published in April 2006