PostgreSQL 9.6 – How to Perform Partial Rollback in Functions

postgresqlpostgresql-9.6transaction

Pseudo code


INSERT INTO table_a
INSERT INTO table_b
RAISE EXCEPTION
UPDATE table_b

Is there a way to keep the inserted table_a tuples but not the table_b tuples when this code exists within a function?

Best Answer

Something like this:

DECLARE _exception_message text; _exception_hint text; BEGIN INSERT INTO table_a BEGIN INSERT INTO table_b RAISE EXCEPTION UPDATE table_b RETURN; EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS _exception_message = MESSAGE_TEXT, _exception_hint = PG_EXCEPTION_HINT; RETURN; END; END

Reference: https://stackoverflow.com/questions/42638907/savepoint-in-postgresql-function