// SQL snippet

List soft-deleted rows that can be restored

Select rows where deleted_at is set and recent enough to be within your retention window, newest first: that is the restore list.

Main statement
PostgreSQL
Também cobre
MySQL

The task

Support asks to un-delete a customer from last week. Soft deletes make that a SELECT away, provided you catch them before retention or a hard-delete job removes them.

The snippet

Written for PostgreSQL. Versions for MySQL are under Variations.

PostgreSQL
SELECT id, email, name, deleted_at
FROM customers
WHERE deleted_at IS NOT NULL
  AND deleted_at >= CURRENT_TIMESTAMP - INTERVAL '30 days'
ORDER BY deleted_at DESC;

Como funciona

The first condition keeps only soft-deleted rows; the second bounds them to the 30-day retention window so the list matches what a restore job would still accept. Ordering by deleted_at DESC puts the freshest undo candidates on top. The variant shows the UPDATE that brings a row back.

Variations

The restore statement itself

BEGIN;
UPDATE customers
SET deleted_at = NULL
WHERE id = 42
  AND deleted_at IS NOT NULL;
-- expect UPDATE 1, then COMMIT; anything else, ROLLBACK;

MySQL version of the window

MySQL
SELECT id, email, name, deleted_at
FROM customers
WHERE deleted_at IS NOT NULL
  AND deleted_at >= NOW() - INTERVAL 30 DAY
ORDER BY deleted_at DESC;

Questions that come up

Should restoring also restore the row's children?

If the parent was soft-deleted with a cascade of soft deletes on its children, yes. A customer restored while their orders stay deleted is a new kind of inconsistency. Either cascade the restore the same way the delete cascaded, or design soft deletes to flag the parent only and derive child visibility from it.

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.