Introduction
Savepoints let you mark spots inside a transaction so you can go back to them if something goes wrong, without undoing the whole transaction.
SAVEPOINT savepoint_name; -- Do some SQL commands ROLLBACK TO savepoint_name; -- Or commit the whole transaction later COMMIT;
BEGIN; SAVEPOINT sp1; INSERT INTO accounts VALUES (1, 'Alice', 100); ROLLBACK TO sp1; COMMIT;
BEGIN; SAVEPOINT sp1; UPDATE accounts SET balance = balance - 50 WHERE id = 1; SAVEPOINT sp2; UPDATE accounts SET balance = balance + 50 WHERE id = 2; ROLLBACK TO sp2; COMMIT;
BEGIN; CREATE TEMP TABLE accounts(id INT, name TEXT, balance INT); INSERT INTO accounts VALUES (1, 'Alice', 100), (2, 'Bob', 50); SAVEPOINT sp1; UPDATE accounts SET balance = balance - 30 WHERE id = 1; SAVEPOINT sp2; UPDATE accounts SET balance = balance + 30 WHERE id = 2; ROLLBACK TO sp2; COMMIT; SELECT * FROM accounts ORDER BY id;
SAVEPOINT in a database transaction?sp1 inside a transaction?SAVEPOINT name; without extra keywords.BEGIN TRANSACTION; INSERT INTO accounts VALUES (1, 100); SAVEPOINT sp1; UPDATE accounts SET balance = balance - 50 WHERE id = 1; ROLLBACK TO SAVEPOINT sp1; COMMIT;
BEGIN TRANSACTION; SAVEPOINT sp1; INSERT INTO orders VALUES (101, 'Book'); ROLLBACK TO sp2; COMMIT;
sp1 is created, but rollback tries to use sp2 which does not exist.Pass the test and this pattern moves unknown