Partial Rollbacks Inside an SQL Transaction: How SAVEPOINT Saves an Order When Payment FailsBrief · digest for November 27
Brief≈ 1 min

Partial Rollbacks Inside an SQL Transaction: How SAVEPOINT Saves an Order When Payment Fails

You open a transaction, insert an order, try to process payment, and hit an error. A regular ROLLBACK wipes out everything, including the valid order—and in PostgreSQL, a failed transaction refuses any further queries until you roll back.

Standard SQL checkpoints via SAVEPOINT solve this. You drop a marker before a risky step, and on failure call ROLLBACK TO SAVEPOINT: everything before the marker stays intact, and the transaction keeps moving.

BEGIN;

INSERT INTO orders VALUES (1, 'Laptop');
-- Set a checkpoint before attempting payment
SAVEPOINT before_payment;

INSERT INTO payments VALUES (1, 'FAILED');
-- Undo only the payment; the order stays intact
ROLLBACK TO SAVEPOINT before_payment;

-- Record a successful payment and drop the checkpoint
INSERT INTO payments VALUES (1, 'SUCCESS');
RELEASE SAVEPOINT before_payment;

COMMIT;

After rolling back, before_payment remains active so you can return to it again, while RELEASE SAVEPOINT clears it without losing data. Just avoid putting SAVEPOINT inside a loop over hundreds of rows: PostgreSQL caches up to 64 subtransactions per backend before spilling to pg_subtrans, which slows things down. For bulk duplicates, use INSERT ... ON CONFLICT instead.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3