For data integrity ON DELETE CASCADE
is necessary but it's really dangerous when a delete affects like a Chain Reaction!
I know one way to prevent this is to make a pseudo delete by putting a "Delete" flag on in all tables where the record is being deleted from. But that's a very old style and clumsy way. How can I optimize this or is there any way to do it from inside database (SQL Code) ?
Best Answer
Perhaps you should look into using tombstone tables.
Here is what I mean: Suppose you had this table
Now, create a table with the IDs that are marked for deletion
So instead of doing
You would add the ids to
mytable_deleted
From here, you simply have to add the mytable_delete to all queries
To see all rows
To see non-deleted rows
To see deleted rows
or
To perform the actual deletion
CAVEAT
This will means that lots of SELECT queries must incorporate the tombstone table.
I have discussed this before : Tombstone Table vs Deleted Flag in database syncronization & soft-delete scenarios. You should read the accepted answer from Leigh Riffel instead of mine for a more honest critique as to which method is better in your case.