Skip to content

Soft delete and trash

With soft delete on, DELETE does not remove the row. It sets deleted_at and hides the row from anon and authenticated, so your app, your policies and your queries keep working without changes. The row sits in a trash you can list, restore and purge. It is opt-in per table and needs no code changes in the app. The dashboard has a Trash tab on every table (developer role and up) that does all of this without SQL.

As the table owner (the SQL editor works; the anon, authenticated and service_role API roles cannot):

select base.enable_soft_delete('public.todos');
select base.enable_soft_delete('public.todos', interval '90 days'); -- keep trashed rows 90 days (0 = forever, minimum 1 hour)
select base.enable_soft_delete('public.todos', null, false); -- trash visible to service_role only
select base.enable_soft_delete('public.posts', p_cascade => false); -- deleting a post does not trash its comments
select base.enable_soft_delete('public.users', p_fix_unique => true); -- unique(email) only counts live rows
select base.disable_soft_delete('public.todos', p_restore => true); -- or p_purge => true
  • The table needs a primary key. Partitioned tables and the audit, auth, base and pg_* schemas are not supported.
  • It adds a nullable deleted_at timestamptz column (the column local-first sync already uses; both features share it), three RESTRICTIVE row-level security policies, two triggers and a small index on the trashed rows.
  • A table without row-level security gets it turned on, plus an allow-all policy, so nothing else changes.
  • Calling it again is safe, but every option you leave out goes back to its default (the last call wins): pass all the options you want to keep. It returns findings: unique constraints that a trashed row still occupies, child tables without soft delete, the reminder to create the purge job.
Operation Result
DELETE /rest/v1/todos?id=eq.1 204. The row is kept with deleted_at = now(). Your DELETE policy still decides who may delete
GET /rest/v1/todos, embeds, views with security_invoker, your own functions The row is gone, even if your policy is using (true)
PATCH or DELETE of a trashed row Affects 0 rows
POST of a primary key that is in the trash 409 (unique violation); with merge-duplicates the request is refused. Restore the row instead
PATCH or POST that writes deleted_at 42501. Only the delete, the restore function and service_role change this column
Prefer: return=representation or count=exact on DELETE Returns no row and 0, because no row was really deleted

TRUNCATE still deletes for good.

Functions are created in the table’s schema and returned as the table’s row type, so select, filters, order and limit all work. They run with the caller’s rights: a user lists, restores and purges what their own select, update and delete policies allow.

GET /rest/v1/rpc/base_trash_todos?order=deleted_at.desc&limit=20
GET /rest/v1/todos?deleted=only&order=deleted_at.desc&limit=20 -- the same, written as a query on the table
POST /rest/v1/rpc/base_restore_todos {"p_pk": {"id": 1}} -- the row is back, deleted_at is null
POST /rest/v1/rpc/base_purge_todos {"p_pk": {"id": 1}} -- deletes a trashed row for good (foreign keys run)
POST /rest/v1/rpc/base_soft_delete_todos {"p_pk": [{"id": 1}, {"id": 2}]} -- deletes many rows in one statement

With the SDK:

const { data } = await base.trash('todos').list().order('deleted_at', { ascending: false }).limit(20)
await base.trash('todos').restore({ id: 1 })
await base.trash('todos').purge({ id: 1 })
await base.trash('todos').remove([{ id: 2 }, { id: 3 }]) // one request, one statement
  • Restoring a row that is not in the trash returns nothing. Restoring into a value another live row now holds (a partial unique index on live rows) fails with 409 and the row stays in the trash.
  • base_purge_* only deletes rows that are already in the trash; it cannot be used to hard-delete a live row.
  • base_soft_delete_* is the fast way to delete thousands of rows: one UPDATE for up to 100,000 keys. A row is deleted only if your DELETE policy and your UPDATE policy would both allow it; the others are skipped.
  • ?deleted=only works on GET and HEAD only. A column named deleted is still filtered the usual way (?deleted=eq.true).
  • With p_user_trash => false these functions are for service_role only.

A trashed row still occupies its unique values, so inserting the same email again fails with 409 until the row is purged. enable_soft_delete reports each such constraint (unique_blocks_reuse). With p_fix_unique => true it replaces the constraint (same name, same columns) by a unique index that only covers live rows (where deleted_at is null) plus a plain index for lookups, and a trashed row no longer blocks the value. A constraint that a foreign key points at, or that is deferrable, stays as it is (unique_referenced). Restoring a row whose value was taken meanwhile fails with 409.

  • on delete cascade to a child table that also has soft delete: deleting the parent trashes its live children with the same deleted_at, down the whole chain. Restoring the parent restores only the children trashed with it; a child you deleted on its own earlier stays in the trash. Use p_cascade => false to turn this off.
  • on delete restrict or no action: a parent with a live child cannot be deleted (409, like a real delete). A child that is already in the trash does not count.
  • cascade, set null to a child without soft delete: the action does not run on a soft delete, so the children stay and point at a trashed row; enable_soft_delete reports it (child_not_soft). The action runs when the parent is purged. Turn soft delete on for the child to cascade.
  • The purge goes children first, so a restrict child that is due too does not block its parent.

Trashed rows older than the retention are removed by base.soft_delete_purge. Retention is per table (second argument of enable_soft_delete) or the database setting base.soft_delete_retention_days (default 30; 0 keeps rows forever).

select base.soft_delete_purge(5000); -- deletes at most 5000 rows, returns how many; call again until 0

Only service_role and the project owner can run it. A project database has no cron schema, so schedule it through the Management API, or press Create purge job in the Trash tab:

POST /v1/projects/{ref}/cron/jobs
{ "name": "base_soft_delete_purge", "schedule": "0 * * * *", "command": "select base.soft_delete_purge(5000)" }

Without the job the trash only grows.

  • Row history. A soft delete is an UPDATE of deleted_at in the log (with the user), a restore is the reverse, and a purge is a DELETE with the old row. Turn on row history to know who deleted what, and do not exclude deleted_at from it.
  • Time-travel. ?as_of= leaves out rows that were in the trash at that moment.
  • Local-first sync. The soft delete is the tombstone: the next pull removes the row from the client and a restore brings it back. Enabling soft delete on a synced table does not bump the epoch.
  • Realtime. A soft delete reaches postgres_changes subscribers as a DELETE event with the primary key only, like a real delete (the row is hidden from them, so an UPDATE would never arrive). A restore arrives as an UPDATE with deleted_at null. A subscription filter on a column other than the key does not match delete events, as for a real delete.
  • Transactions. Everything happens in the transaction of the original statement.
  • Only the API roles are protected. SQL run as the table owner, service_role, SECURITY DEFINER functions and views that are not security_invoker still see trashed rows; filter on deleted_at is null there.
  • The triggers that soft delete adds run as the owner of the table, so your own triggers on the table see current_user = that owner while a row is trashed, restored or purged. Child tables that cascade should have the same owner.
  • A no action foreign key that is deferrable is not checked on a soft delete.
  • DROP TABLE needs base.disable_soft_delete(...) first, or DROP TABLE ... CASCADE.
  • A DELETE from PostgREST is a soft delete per row: deleting 50,000 rows in one statement is much slower than a hard delete. Use base_soft_delete_<table> (one statement) or delete in batches.
  • If you use base.enable_audit on the table, do not exclude deleted_at: time-travel (?as_of=) needs its history, so base.enable_audit refuses it (and base.enable_soft_delete refuses a table whose audit excludes it).