SQL - Transactions

Overview

Transactions group statements to succeed or fail as a unit (ACID). Use them for correctness.

START TRANSACTION;
UPDATE employees SET salary = salary * 1.1 WHERE department_id = 1;
-- if all good
COMMIT;
-- otherwise ROLLBACK;
BEGIN TRAN;
UPDATE employees SET salary = salary * 1.1 WHERE department_id = 1;
COMMIT TRAN;  -- or ROLLBACK TRAN
BEGIN TRANSACTION;
UPDATE employees SET salary = salary * 1.1 WHERE department_id = 1;
COMMIT; -- or ROLLBACK

Savepoints

SAVEPOINT sp1;
-- do something
ROLLBACK TO sp1;
SAVE TRAN sp1;
-- do something
ROLLBACK TRAN sp1;
SAVEPOINT sp1;
-- do something
ROLLBACK TO sp1;
RELEASE sp1;