Home >Database >Mysql Tutorial >How Does ON DELETE CASCADE Affect Related Tables in MySQL Foreign Key Constraints?
MySQL Foreign Key Constraints with Cascade Delete
Foreign key constraints play a vital role in maintaining data integrity and preventing orphans in relational databases. In MySQL, you can use the ON DELETE CASCADE option to ensure that when you delete a parent record, related child records are automatically deleted as well.
To set up a foreign key constraint with cascade delete, consider the following tables:
In this setup, products has a foreign key referencing categories, and ON DELETE CASCADE is specified to automatically delete products when the referenced category is deleted. However, this cascade will only affect records in categories_products where the category_id matches the deleted category.
For example, if you have the following data:
If you delete the 'red' category:
The products table will not be affected because the cascade only applies to the categories_products table. As a result, the data will become:
This arrangement ensures that you can maintain referential integrity while avoiding unintentional deletion of unrelated records.
The above is the detailed content of How Does ON DELETE CASCADE Affect Related Tables in MySQL Foreign Key Constraints?. For more information, please follow other related articles on the PHP Chinese website!