Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting database records unpermenantley (soft-delete)

The Story

I'm going to write up some code to manage the deleted items in my application, but I'm going to soft delete them so I could return them back when I need. I have a hierarchy to respect in my application's logic when it comes to hiding or deleting items.

I logically place my items in three containers to the country, city, district and brand. Each item should belong to a country, a city, a district and a brand. Now, if I deleted a country it should delete the cities, districts, brands, and items that belongs to the given country. and if I deleted the city it should also delete the whole stuff under it (districts, brands, etc)


A Note

When I delete a country and delete the associated brands, I should take care that a brand might have items in more than one country.


The Question

Do you suggest to

  1. Flag the items (whether it's country, city, item, etc) as deleted and this will require a lot of code to check every time when any item is loaded from the database, if it's deleted or not and also some extra fields to mark if the city it belongs to is deleted, and the country it belongs to is deleted and so on.

  2. Move the deleted stuff each to a specific table (DeletedCountries, Deleted Cities, etc) and save the the IDs of the items it was associated with so I could insert them back later to it's original table. and of course this will save my application all the code that will manage to check all the deleted items and make sure all the hierarchy is deleted.

  3. Maybe you have a better approach/advice/idea about achieving such a thing!

like image 570
Mazen Elkashef Avatar asked Mar 09 '11 03:03

Mazen Elkashef


People also ask

What is difference between delete and soft delete?

Hard vs soft deletesA “hard” delete is when rows are deleted using DELETE FROM table WHERE ... A “soft” delete is when rows are deleted using UPDATE table SET deleted_at = now() WHERE ...

What is soft delete and hard delete in database?

Hard Deletes — The entire record is deleted from the table. After the delete, users will not be able to see that the record ever existed. Soft Deletes — The record is not removed from the table, but a field on the table indicates that it is deleted.

What is soft delete in database?

soft deletion (plural soft deletions) (databases) An operation in which a flag is used to mark data as unusable, without erasing the data itself from the database.


1 Answers

For argument's sake, one advantage of solution #2 (moving deleted items to their own tables) is if you have lots and lots of records, you would not have to worry about indexing records in respect to their "deleted" state.

With that said, if I were going to "move" data from table to table (via delete followed by insert) I would make sure to do it in 1 transaction.

like image 109
dana Avatar answered Oct 19 '22 23:10

dana