Paste this into a new question or an answer at dba.stackexchange.com:
<!-- --> > create table test > ( > id serial primary key, > name varchar(128) not null > ); > > <pre> > ✓ > </pre> <!-- --> > create table test_archive > ( > id serial primary key, > name varchar(128) not null > ); > > <pre> > ✓ > </pre> <!-- --> > CREATE OR REPLACE FUNCTION archive_record() > RETURNS TRIGGER AS $$ > BEGIN > RAISE NOTICE 'Running trigger'; > EXECUTE format('INSERT INTO %I.%I SELECT $1.*', TG_TABLE_SCHEMA, (TG_TABLE_NAME || '_archive')) > USING OLD; > RETURN NULL; > END; > $$ LANGUAGE PLPGSQL; > > <pre> > ✓ > </pre> <!-- --> > CREATE TRIGGER delete_test > AFTER DELETE > ON test > FOR EACH ROW > EXECUTE PROCEDURE archive_record(); > > <pre> > ✓ > </pre> <!-- --> > insert into test values (1,'test1'),(2,'test2') > > <pre> 2 rows affected > </pre> <!-- --> > DELETE FROM test WHERE id = 1 > > <pre> 1 rows affected > </pre> <!-- --> > SELECT * FROM test_archive > > <pre> > id | name > -: | :---- > 1 | test1 > </pre> <!-- --> > SELECT * FROM test > > <pre> > id | name > -: | :---- > 2 | test2 > </pre> *db<>fiddle [here](https://dbfiddle.uk/?rdbms=postgres_12&fiddle=37fa645395fc8e06461e32929d7f5f57)*
back to fiddle