HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Implementing soft delete

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
implementingdeletesoft

Problem

Could someone please show or describe to me how to implement soft deletes?

I have table of vouchers with these fields: id, username, password, serial.

I want to display a given number of rows depending on the customer's request
and once displayed they should be deleted so that the are not displayed again. (They are already invalid.)

I presume soft delete will ensure that no voucher is displayed twice.
If you have any other idea on how I would do it I would appreciate.

Solution

I have always implemented a Soft Delete by including two additional columns in my tables, one for status and one for delete date.

My table structure would be similar to the following:

create table myTable
(
  id int,
  name varchar(50),
  IsDeleted bit,
  DeletedDate datetime
);


The IsDeleted column has a default value of no and the DeletedDate is not populated until the row is actually marked as deleted. I include a date column in the event I ever want to know when a row was soft deleted.

Then when you query your data, you will include this column in the WHERE clause:

select id, name
from myTable
where IsDeleted = 0


Note: You will want to include an index on the IsDeleted column.

Code Snippets

create table myTable
(
  id int,
  name varchar(50),
  IsDeleted bit,
  DeletedDate datetime
);
select id, name
from myTable
where IsDeleted = 0

Context

StackExchange Database Administrators Q#36558, answer score: 11

Revisions (0)

No revisions yet.