Video in progress

Why do you need `SAVEPOINT` inside a transaction, and how do you "rescue" a transaction after an error in PostgreSQL?

In PostgreSQL, a single error inside a transaction puts the whole transaction into an "aborted" state, and every following query is rejected. If you set a SAVEPOINT and run ROLLBACK TO SAVEPOINT after the error, you undo only that part and can carry on.

📖 Answer

For example, during an import one row hits a unique constraint:

BEGIN;
INSERT INTO customers ... ;            -- ok
INSERT INTO customers ... ;            -- ERROR: duplicate key
INSERT INTO customers ... ;            -- ERROR: current transaction is aborted,
                                       -- commands ignored until end of transaction block

With a savepoint:

BEGIN;
SAVEPOINT row_1;
INSERT INTO customers ... ;            -- error
ROLLBACK TO SAVEPOINT row_1;           -- only this insert is undone
INSERT INTO customers ... ;            -- works
COMMIT;

In JDBC there are connection.setSavepoint() and connection.rollback(savepoint). In Spring, Propagation.NESTED works exactly through a savepoint (with DataSourceTransactionManager).

Where to be careful: a savepoint for every row is expensive, and thousands of savepoints slow the transaction down. In many cases INSERT ... ON CONFLICT DO NOTHING or checking the data up front is a simpler solution.