Is it safe to rely on MySQL Cascade for delete Is it safe to rely on MySQL Cascade for delete laravel laravel

Is it safe to rely on MySQL Cascade for delete


Yes, you can rely on CASCADE deletes. If you define a relationship with ON DELETE CASCADE, the foriegn row will definitely be deleted. Using ON DELETE CASCADE is definitely reccommended (assuming you want to delete the related rows), and it is likely more reliable than implementing the delete cascade in your application.

In the example you gave, the rows containing the users posts were related to the user using a foreign key with ON DELETE CASCADE. In this case, you would just delete the user. MySQL will follow all of the relationships and delete all related rows. This wil prevent orphaned data. Doing it via the application is much more "risky" in terms of the potential for orphaning data.

Keep in mind, however, if there are other relationships to the same data (e.g. there are reply posts relating to the user's post who is going to be deleted), the delete can be blocked, since the reference in the reply row would be dangling. Of course, this is all dependent on your database design and how you set up your foreign keys.