Skip to content

Instantly share code, notes, and snippets.

@kendru
Created September 16, 2025 20:19
Show Gist options
  • Save kendru/11188ccaab191d8906296539c66d4c03 to your computer and use it in GitHub Desktop.
Save kendru/11188ccaab191d8906296539c66d4c03 to your computer and use it in GitHub Desktop.
Example of transparent soft-deletes in Postgres
create table widget_history (
id bigint generated always as identity,
name text not null,
created_at timestamp not null default current_timestamp,
deleted_at timestamp
);
create index widget_by_name on widget_history(name) where deleted_at is null;
create view widget as
select * from widget_history where deleted_at is null;
create or replace function soft_delete()
returns trigger as $$
declare
target_tbl text;
update_query text;
begin
target_tbl := tg_table_name || '_history';
update_query := format(
'update %I set deleted_at = current_timestamp where id = $1',
target_tbl
);
execute update_query using old.id;
return null;
end;
$$ language plpgsql;
create trigger widget_soft_delete_trigger
instead of delete on widget
for each row
execute function soft_delete();
---
insert into widget (name)
values ('Thungummy'), ('Whatchamacallit');
select * from widget;
-- id | name | created_at | deleted_at
-- ----+-----------------+----------------------------+------------
-- 1 | Thingummy | 2025-09-16 17:49:39.177458 |
-- 2 | Whatchamacallit | 2025-09-16 17:49:56.544898 |
-- (2 rows)
delete from widget where name like 'What%';
select * from widget;
-- id | name | created_at | deleted_at
-- ----+-----------------+----------------------------+------------
-- 1 | Thingummy | 2025-09-16 17:49:39.177458 |
-- (1 row)select * from widget;
select * from widget_history;
-- id | name | created_at | deleted_at
-- ----+-----------------+----------------------------+---------------------------
-- 1 | Thingummy | 2025-09-16 17:49:39.177458 |
-- 2 | Whatchamacallit | 2025-09-16 17:49:56.544898 | 2025-09-16 18:38:26.842889
-- (2 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment