Archive deleted PostgreSQL rows by copying them to another table
A minimal example for PostgreSQL on how to copy database rows into another table when they are deleted in the original table.
CREATE OR REPLACE FUNCTION my_schema.archive_MyTable()
RETURNS TRIGGER AS
$$
BEGIN
INSERT INTO my_schema."MyTable_ARCH"(
"Id_ARCH" -- Add other necessary columns here
)
VALUES (
OLD."Id" -- Add other necessary columns here
);
RETURN OLD;
END;
$$
LANGUAGE plpgsql;
ALTER FUNCTION my_schema.archive_MyTable() OWNER TO postgres;
CREATE TRIGGER MyTable_archive_MyTable
AFTER DELETE ON my_schema."MyTable"
FOR EACH ROW EXECUTE FUNCTION my_schema.archive();
grant select,insert on table my_schema."MyTable_ARCH" TO my_user;
GRANT ALL ON FUNCTION my_schema.archive_MyTable() TO my_user;
GRANT ALL ON SEQUENCE my_schema."MyTable_ARCH_Id_seq" TO my_user;