Articles

Soft Delete vs Hard Delete: Database Deletion Patterns

Soft delete marks a row as deleted with a flag or timestamp; hard delete removes it. Trade-offs for recovery, queries, constraints, and privacy.

The Lycoris Team The Lycoris Team · · 5 min read
Rows of server hardware in a data center

A soft delete marks a row as deleted, usually by setting a deleted_at timestamp, while leaving the data in the table. A hard delete runs an actual DELETE and removes the row. Soft deletes make recovery and auditing easy but push complexity into every query; hard deletes keep the schema honest but make mistakes permanent. Which one fits depends on whether you value undo, simplicity, or the guarantee that data is truly gone.

How a soft delete works

The typical implementation adds a nullable column:

ALTER TABLE projects ADD COLUMN deleted_at timestamptz;

-- "Delete" a project
UPDATE projects SET deleted_at = now() WHERE id = 42;

-- Every normal read must now filter
SELECT * FROM projects WHERE deleted_at IS NULL;

A timestamp is more useful than a boolean is_deleted flag because it records when the deletion happened at no extra cost, which helps with retention jobs and debugging. Some teams also add deleted_by to capture who did it.

How a hard delete works

A hard delete is just DELETE FROM projects WHERE id = 42;. The row is gone from the table’s visible state. Foreign keys decide what happens to dependent rows: ON DELETE CASCADE removes them too, ON DELETE RESTRICT blocks the delete, and ON DELETE SET NULL detaches them. The database enforces those rules for you, which is one of the quiet advantages of hard deletes.

Soft delete vs hard delete compared

Soft deleteHard delete
UndoTrivial: clear the timestampRequires a backup or audit log
Query complexityEvery read needs a filterNo extra filtering
Unique constraintsNeed partial indexes to work correctlyWork as written
Foreign key cascadesNot triggered; handled in app codeEnforced by the database
Table growthGrows indefinitely without cleanupStays proportional to live data
Privacy and erasure requestsData still presentData removed from the table
Audit trailBuilt in, partiallyNeeds a separate mechanism

The case for soft deletes

Recovery is instant. Users delete things by accident. Support teams can restore a soft-deleted record with a single update instead of digging through backups or attempting a point-in-time recovery for one row.

History stays intact. An invoice that references a deleted customer still makes sense if the customer row exists. Reports over past periods keep matching what people saw at the time.

Deletion becomes a reversible state change. Many products want a “trash” with a grace period. Soft delete is the natural backing for that feature, with a scheduled job that hard-deletes anything older than the retention window.

The costs of soft deletes

Every query has to remember the filter. One forgotten WHERE deleted_at IS NULL and deleted records reappear in a list, a count, or an export. ORMs often offer a default scope to help, but raw SQL, reporting tools, and new teammates will not know about it. A common mitigation is a view that exposes only live rows, so application code reads from the view instead of the base table. Our comparison of views and materialized views covers the trade-offs.

Unique constraints break. If email is unique and a user soft-deletes their account, nobody can sign up with that email again, because the old row still holds it. The fix is a partial unique index that only covers live rows:

CREATE UNIQUE INDEX users_email_live
  ON users (email)
  WHERE deleted_at IS NULL;

The same technique keeps indexes small by excluding dead rows, which is covered in more depth in PostgreSQL partial indexes.

Cascades become your job. Soft-deleting a project does not soft-delete its tasks. Application code has to walk the relationships, or you accept that children of deleted parents linger in a half-visible state.

Tables only grow. Without a purge job, soft-deleted rows accumulate forever, bloating tables and indexes and slowing scans.

Privacy changes the calculation

When a person asks for their data to be erased, a soft-deleted row is not erased. It is still in the table, still in backups, and still readable by anyone with database access. For personal data, soft delete is at best a grace period before a real deletion, not a substitute for one.

A workable pattern is to soft-delete immediately for user-facing undo, then hard-delete or irreversibly anonymize the personal fields after a fixed window. Document how backups age out as well, since a hard delete in the primary database does not reach copies already taken.

Alternatives to the deleted_at column

Archive tables. Move deleted rows into a separate projects_archive table inside the same transaction. The main table stays clean, constraints work normally, and restoring means moving the row back. The cost is keeping two schemas in sync during migrations.

Event or audit logs. Hard-delete the row but record the deletion, and ideally the old values, in an append-only log. Change data capture can stream every delete to another system automatically, which gives you an audit trail without touching application queries.

Status columns. Sometimes “deleted” is really a business state such as archived, cancelled, or closed. Modeling it explicitly as a status is often clearer than overloading a deletion flag, because the product genuinely needs to display and query those records.

A note on physical deletion

Even a hard delete does not immediately wipe bytes from disk in most databases. In PostgreSQL, a deleted row becomes a dead tuple that remains until vacuuming reclaims the space. That is an implementation detail for performance, not a privacy guarantee either way, but it explains why table size does not always shrink after a large delete.

How to choose

  • Use hard deletes for data with no recovery value: sessions, temporary tokens, cache tables, and join rows that are cheap to recreate.
  • Use soft deletes for user-created content where accidental deletion is costly and a trash or undo feature is expected, paired with a purge job.
  • Use archive tables or audit logs when you need history but want the main table and its constraints to stay simple.
  • For personal data, plan for a real deletion at the end, whatever you do first.

The takeaway

Soft delete trades query simplicity for recoverability: every read needs a filter, unique constraints need partial indexes, and cascades move into application code. Hard delete keeps the database honest and makes erasure real, but mistakes are permanent without backups or logs. Most mature systems combine them, soft-deleting for a grace period and hard-deleting afterward.

The Lycoris Team The Lycoris Team · · 5 min read

UUID vs Auto-Increment Primary Keys: Which to Use

UUIDs vs auto-increment primary keys: sequential integers are compact and index-friendly, UUIDs are globally unique and unguessable. How to choose.

#Databases #SQL #Backend