BEGIN, COMMIT and ROLLBACK: transaction boundaries
Overview
A transaction groups database operations into one unit of work. BEGIN starts an explicit transaction, COMMIT makes its successful changes final, and ROLLBACK discards its uncommitted changes. Load versions/v54/transaction-fixture.sql in a fresh SQLite database before each example; enable foreign keys on that connection. All examples use integer cents, not floating-point money. The first example commits a transfer of 30 cents from account 1 to account 2.
First example
BEGIN;UPDATE tx_account SET cents=cents-30 WHERE id=1;UPDATE tx_account SET cents=cents+30 WHERE id=2;COMMIT;SELECT id,cents FROM tx_account ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 70 ], [ 2, 80 ]]How it works
The balances begin at 100 and 50. Subtracting and adding the same amount preserves the total of 150. The fixed account IDs exist and have sufficient funds. A real application must check that both updates affect exactly one row, validate the amount, and roll back on any error or missing account; a zero-row update is not automatically an SQL error. COMMIT is not a backup, and an already committed transfer cannot be undone by a later ROLLBACK. The second example cancels the same transfer. Both SQLite and PostgreSQL support these boundaries; client transaction settings matter.
Practical example
BEGIN;UPDATE tx_account SET cents=cents-30 WHERE id=1;UPDATE tx_account SET cents=cents+30 WHERE id=2;ROLLBACK;SELECT id,cents FROM tx_account ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 100 ], [ 2, 50 ]]Practice and mistakes
Practice: transfer 15 cents from account 2 to account 1, predict the committed balances and total, then repeat against a fresh fixture with rollback. Hint 1: the total should stay unchanged. Hint 2: use one transaction around both updates and verify both account rows. Avoid executing these examples against real financial data.