A transaction is a sequence of one or more SQL operations executed as a single unit of work. Either all succeed (commit) or all fail (rollback), ensuring data integrity.
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;
-- Transfer happens only if both updates succeed
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
-- Oops! Something went wrong
ROLLBACK;
START TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
SAVEPOINT step1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
ROLLBACK TO step1;
COMMIT;