- Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table.
- If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
- If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table.
- The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.
Here is a demo on how to do it:
1. Create tables.2. Add foreign key.
4. Specify ON DELETE CASCADE.
5. Delete a row in the parent table.
6. Child table rows got deleted as well.
If you having a M-to-M relationship, it is the same. Just add the cascade delete on the M-to-M table.
Reference: