← Back to SQL, page 16

sql-0320 · Medium mid

How would you implement soft delete, and what problems does it introduce?

Add a deleted_at timestamp and treat rows with a value as deleted. Every query must then exclude deleted rows, unique constraints must ignore them (a partial unique index WHERE deleted_at IS NULL), and foreign keys no longer stop references to deleted rows. A view of active rows and a retention job keep it manageable.

Full answer
sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX users_email_active ON users(email) WHERE deleted_at IS NULL;
INSERT INTO users VALUES (1, 'a@x.com', '2026-01-01');
INSERT INTO users VALUES (2, 'a@x.com', NULL);
CREATE VIEW active_users AS SELECT id, email FROM users WHERE deleted_at IS NULL;
SELECT * FROM active_users;
idemail
2a@x.com

The partial unique index lets a deleted account and a new account share an email, while two active accounts cannot. A plain UNIQUE on email would block re-registration after deletion.

Problems to plan for:

  • Every query needs WHERE deleted_at IS NULL; an active_users view helps.
  • Foreign keys still point at soft-deleted rows; cascading deletes do not happen.
  • Tables grow forever unless a job purges old deleted rows.
  • Privacy laws may require real deletion of personal data, which soft delete does not provide.

Alternatives include moving deleted rows to an archive table, or event logs that record the deletion while the row is removed.

sql
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL, deleted_at TEXT);
CREATE UNIQUE INDEX users_email_active ON users(email) WHERE deleted_at IS NULL;
INSERT INTO users VALUES (1, 'a@x.com', '2026-01-01');
INSERT INTO users VALUES (2, 'a@x.com', NULL);
CREATE VIEW active_users AS SELECT id, email FROM users WHERE deleted_at IS NULL;
SELECT * FROM active_users;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • deleted_at marks rows as deleted
  • Partial unique indexes ignore deleted rows
  • Views simplify filtering active rows
  • Plan retention and real deletion for privacy

Common mistakes

  • A plain UNIQUE constraint that blocks re-registration
  • Forgetting the deleted filter in one query

Follow-ups

  • How would you restore a soft-deleted row safely?
  • How do privacy rules affect soft delete?

Tips

  • Mention the unique-constraint fix