// dialect comparison

SAVEPOINT and ROLLBACK TO in every SQL dialect

Savepoints let you undo the last steps of a transaction without discarding everything, the standard tool for per-row error recovery in bulk loads.

Filed under Sessions & admin

The verdict

Every engine can partially roll back; only the spelling differs. SQL Server says SAVE TRANSACTION, the other four say SAVEPOINT. Savepoints matter most in PostgreSQL, where an error otherwise aborts the entire transaction.

Where they differ

PostgreSQL, MySQL, SQLite and Oracle share the SAVEPOINT / ROLLBACK TO syntax, and Oracle skips RELEASE. SQL Server uses SAVE TRANSACTION with a name.

How each engine writes it

SQL Server

BEGIN TRANSACTION;
SAVE TRANSACTION sp1;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TRANSACTION sp1;
COMMIT;

SAVE TRANSACTION names a point; ROLLBACK TRANSACTION sp1 undoes just the work after it and leaves the transaction open. Under SET XACT_ABORT ON most errors roll back the whole transaction, savepoint or not.

PostgreSQL

BEGIN;
SAVEPOINT sp1;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO sp1;
RELEASE SAVEPOINT sp1;
COMMIT;

Any error aborts the whole PostgreSQL transaction, so a savepoint is how you recover: ROLLBACK TO sp1 clears the error and the transaction carries on. Drivers use this for statement-level retry.

MySQL

BEGIN;
SAVEPOINT sp1;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO sp1;
RELEASE SAVEPOINT sp1;
COMMIT;

Standard syntax; works in InnoDB. Savepoints disappear when the transaction commits or rolls back.

SQLite

BEGIN;
SAVEPOINT sp1;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO sp1;
RELEASE SAVEPOINT sp1;
COMMIT;

Fully supported, including RELEASE sp1 collapsing the savepoint. Even usable outside an explicit BEGIN, acting as its own transaction.

Oracle

SAVEPOINT sp1;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK TO sp1;
COMMIT;

Supported in SQL and PL/SQL. Names are reused within a transaction (re-declaring moves the point). No RELEASE statement; points vanish at COMMIT/ROLLBACK.

Questions that come up

Savepoint vs nested transaction?

SQL Server counts nested BEGIN TRANSACTION calls in @@TRANCOUNT: an inner COMMIT only decrements the counter, and a ROLLBACK without a savepoint name undoes everything. Savepoints are the only way to undo part of a transaction, in SQL Server and everywhere else.

Can I release a savepoint and keep the changes?

RELEASE keeps the changes made since the savepoint but removes the ability to roll back to it. SQL Server has no RELEASE; the point is only discarded at commit.

Do savepoints survive a rollback?

ROLLBACK TO sp1 keeps sp1 and earlier points but discards later ones. A full ROLLBACK discards all of them.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.