// SQL snippet

Audit soft-deleted rows

deleted_at IS NULL marks live rows; everything else is soft-deleted, and a few invariants over the timestamps catch misbehaving writes.

Main statement
All engines

The task

customers uses deleted_at for soft deletes. Over time you want to know the live-to-deleted ratio, when deletions happened, and whether any supposedly-deleted row was modified afterwards, which is a bug signature.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT
  COUNT(*) AS total_rows,
  SUM(CASE WHEN deleted_at IS NULL THEN 1 ELSE 0 END) AS live_rows,
  SUM(CASE WHEN deleted_at IS NOT NULL THEN 1 ELSE 0 END) AS deleted_rows,
  SUM(CASE WHEN deleted_at IS NOT NULL AND updated_at > deleted_at
           THEN 1 ELSE 0 END) AS touched_after_delete
FROM customers;

工作原理

Three SUM(CASE) flags split the table: live, soft-deleted, and (the interesting one) rows whose updated_at moved past their deleted_at, which means a write path ignores the soft-delete flag. A healthy table shows touched_after_delete = 0. The variant breaks deletions out per month for a trend view; on other engines swap strftime for to_char(deleted_at, 'YYYY-MM') (PostgreSQL, Oracle), DATE_FORMAT(deleted_at, '%Y-%m') (MySQL) or FORMAT(deleted_at, 'yyyy-MM') (SQL Server).

Variations

Deletions per month (SQLite strftime)

SQLite
SELECT strftime('%Y-%m', deleted_at) AS deletion_month,
       COUNT(*) AS deleted_rows
FROM customers
WHERE deleted_at IS NOT NULL
GROUP BY strftime('%Y-%m', deleted_at)
ORDER BY deletion_month;

Questions that come up

How do rows get updated after deletion?

Usually a query somewhere forgot the WHERE deleted_at IS NULL clause: a background job, an import upsert, or an admin tool. Each hit in touched_after_delete is one of those queries. Fix the query, not just the rows, or the count starts growing again next week.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.