Multiple table delete: Cascade delete vs Join Delete

There is this really old php/mysql project that I maintain and every know and than there are some problems with data integrity, orphaned records and constraint violations.

After some debugging I found out that the main problem is that related data is deleted in separate delete statements, and some of them throw exceptions and don't get executed.

I immediately thought of making a CASCADE DELETE on the constraints, but as I started reading on google about cascades I found out that many people are against it. Personally I have had at least 2 or 3 bad experiences with accidentally deleting some data and then reflecting that on the cascaded data. Probably that is why I try to avoid cascading.

The other option is to make an inner join on the delete statement.

Let's say that we have such a model: User 1:N Service 1:N Service_Parameter

The query would look something like this:

delete user.*, service.*, service_parameters.* 
from user 
inner join service on service.user_id = user.id 
inner join service_parameter on service_parameter.service_id = service.id 
where user.id = $id


People seem to be against this idea as you would have to remember the data relation and execute such a query whenever you are deleting data. However if your application code is written properly you would usually have a delete method where this query would be written, and then execute this method (or stored procedure) whenever you want to delete something.

If you delete something manually from the DB, accidentally or intentionally, you would not delete the cascaded data. This might be a pro or a con whichever way you want to look at it.

Perssonally I would like to have to make more separate deletes or a stored procedure with the above query rather than using the dreaded CASCADE DELETE and not having an explicit control of what am I deleting.

No comments:

Post a Comment