Savepoint Rolls Back Part Of Transaction

Mark a point inside a transaction with SAVEPOINT so a failed statement can be undone with ROLLBACK TO SAVEPOINT while earlier work stays intact.

SqlData Integrity

Code

snippet
BEGIN;

INSERT INTO ledger (account, cents) VALUES ('checking', 5000);

SAVEPOINT before_bonus;

INSERT INTO ledger (account, cents) VALUES ('bonus', 999999);
-- 假设这一行金额校验不过:只撤销 SAVEPOINT 之后的部分

ROLLBACK TO SAVEPOINT before_bonus;

-- 事务仍处于打开状态,前面的 checking 写入原样保留
INSERT INTO ledger (account, cents) VALUES ('bonus', 25000);

RELEASE SAVEPOINT before_bonus;
COMMIT;

How it works

The file scripts one transaction against the ledger table in four stages. BEGIN; opens it and INSERT INTO ledger (account, cents) VALUES ('checking', 5000); writes the first row. SAVEPOINT before_bonus; then marks a named point inside the transaction.

The bonus insert with the over-limit amount ('bonus', 999999) stands in for the failure case the comment describes (“assume this row’s amount validation fails”). ROLLBACK TO SAVEPOINT before_bonus; undoes only the work after that marker — the transaction stays open and the earlier checking insert survives untouched, which the comment calls out explicitly. The corrected INSERT ... VALUES ('bonus', 25000); re-runs, RELEASE SAVEPOINT before_bonus; discards the marker, and COMMIT; persists both surviving rows.

What to watch for

  • ROLLBACK TO SAVEPOINT is not ROLLBACK: the transaction does not end, and everything before the savepoint is kept — that asymmetry is the whole point of the pattern.
  • After RELEASE SAVEPOINT, the marker no longer exists; rolling back to it again would fail.

Using it

Adapt the pattern by naming a savepoint before the risky statement, rolling back to it when validation fails, and releasing it once the retry succeeds — here the ledger table and the two (account, cents) value pairs show the shape end to end.

Key statements

INSERT INTO ledger (account, cents) VALUES ('checking', 5000);
INSERT INTO ledger (account, cents) VALUES ('bonus', 999999);
INSERT INTO ledger (account, cents) VALUES ('bonus', 25000);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `ledger`.