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.
Turn it on
Section titled “Turn it on”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 onlyselect base.enable_soft_delete('public.posts', p_cascade => false); -- deleting a post does not trash its commentsselect base.enable_soft_delete('public.users', p_fix_unique => true); -- unique(email) only counts live rowsselect 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,baseandpg_*schemas are not supported. - It adds a nullable
deleted_at timestamptzcolumn (the column local-first sync already uses; both features share it), threeRESTRICTIVErow-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.
Two behaviors to know
Section titled “Two behaviors to know”What changes for your app
Section titled “What changes for your app”| 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.
The trash
Section titled “The trash”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=20GET /rest/v1/todos?deleted=only&order=deleted_at.desc&limit=20 -- the same, written as a query on the tablePOST /rest/v1/rpc/base_restore_todos {"p_pk": {"id": 1}} -- the row is back, deleted_at is nullPOST /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 statementWith 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
409and 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: oneUPDATEfor up to 100,000 keys. A row is deleted only if yourDELETEpolicy and yourUPDATEpolicy would both allow it; the others are skipped.?deleted=onlyworks onGETandHEADonly. A column nameddeletedis still filtered the usual way (?deleted=eq.true).- With
p_user_trash => falsethese functions are forservice_roleonly.
Unique values
Section titled “Unique values”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.
Child tables
Section titled “Child tables”on delete cascadeto a child table that also has soft delete: deleting the parent trashes its live children with the samedeleted_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. Usep_cascade => falseto turn this off.on delete restrictor 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 nullto 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_deletereports 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
restrictchild that is due too does not block its parent.
Clean up after N days
Section titled “Clean up after N days”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 0Only 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.
With the other features
Section titled “With the other features”- Row history. A soft delete is an
UPDATEofdeleted_atin the log (with the user), a restore is the reverse, and a purge is aDELETEwith the old row. Turn on row history to know who deleted what, and do not excludedeleted_atfrom 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_changessubscribers as aDELETEevent with the primary key only, like a real delete (the row is hidden from them, so anUPDATEwould never arrive). A restore arrives as anUPDATEwithdeleted_atnull. 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.
Limits
Section titled “Limits”- Only the API roles are protected. SQL run as the table owner,
service_role,SECURITY DEFINERfunctions and views that are notsecurity_invokerstill see trashed rows; filter ondeleted_at is nullthere. - 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 actionforeign key that is deferrable is not checked on a soft delete. DROP TABLEneedsbase.disable_soft_delete(...)first, orDROP TABLE ... CASCADE.- A
DELETEfrom PostgREST is a soft delete per row: deleting 50,000 rows in one statement is much slower than a hard delete. Usebase_soft_delete_<table>(one statement) or delete in batches. - If you use
base.enable_auditon the table, do not excludedeleted_at: time-travel (?as_of=) needs its history, sobase.enable_auditrefuses it (andbase.enable_soft_deleterefuses a table whose audit excludes it).