Difficulty: Beginner
What is a soft delete, how do you implement it correctly, and what problems does it introduce compared to a hard delete?
A soft delete marks a row as deleted, usually by setting a deleted_at timestamp or an is_deleted flag, instead of physically removing it with DELETE. Queries then filter out marked rows so the application behaves as if the data is gone. It makes recovery, auditing and undo easy, but every query must remember the filter, unique constraints need special handling, and the data is still stored, which matters for privacy laws.
deleted_at TIMESTAMPTZ column. NULL means active; a timestamp means deleted and records when. This is more useful than a boolean because you know when it happened and can purge old rows.DELETE FROM users WHERE id = 7 with UPDATE users SET deleted_at = now() WHERE id = 7.WHERE deleted_at IS NULL to every read, ideally centrally:active_users,SoftDeletes trait, Hibernate's @SQLDelete with @SQLRestriction (which replaced @Where in Hibernate 6.3), or a Prisma client extension,deleted_at IS NULL shows deleted data. This is the most common bug.UNIQUE(email) rejects it. Fix with a partial unique index: CREATE UNIQUE INDEX ... ON users(email) WHERE deleted_at IS NULL in PostgreSQL. MySQL lacks partial indexes, so teams use a generated column or include deleted_at in the key with care about NULL handling.ON DELETE CASCADE never fires because nothing is deleted. You must soft delete children yourself or accept orphaned-looking data.| Approach | How it works | Good for |
|---|---|---|
| Soft delete flag | deleted_at on the same table | Undo, short retention |
| Archive table | Move row to users_deleted in a transaction, then hard delete | Keeping live tables clean |
| Audit / history table | Trigger or CDC copies every change | Full history and compliance |
| Hard delete plus backups | Physical delete, restore from backup if needed | Simple data with no undo |
A common production pattern: soft delete immediately, then a scheduled job hard deletes or anonymises rows older than a retention window such as 30 or 90 days.
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;
-- Email must be unique only among active users
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key;
CREATE UNIQUE INDEX uq_users_email_active
ON users (email) WHERE deleted_at IS NULL;
-- Soft delete
UPDATE users SET deleted_at = now() WHERE id = 7;
-- Central place for the filter
CREATE VIEW active_users AS
SELECT * FROM users WHERE deleted_at IS NULL;
-- Nightly purge after 90 days
DELETE FROM users WHERE deleted_at < now() - INTERVAL '90 days';
The partial index lets a deleted user's email be reused, the view centralises the filter, and the purge keeps the table from growing forever.
Soft Delete, deleted_at, Partial Unique Index, Data Retention, Right to Erasure