COMMIT & ROLLBACK
Once you have started a transaction with
BEGIN, every statement you run is provisional — nothing is permanent until you say so. COMMIT and ROLLBACK are the two ways a transaction ends: one keeps the changes, the other discards them.COMMIT — save the changes
COMMIT permanently saves every change made since the transaction began. Once committed, the changes are durable — they survive crashes, restarts, and are visible to every other connection to the database.A successful transfer
SQL
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
After
COMMIT runs, both updates are final. There is no way to undo them except by running new, compensating statements.ROLLBACK — undo the changes
ROLLBACK undoes every change made since the transaction began, as if none of the statements had ever run. This is what protects you when something goes wrong midway through a multi-step operation.Backing out of a transfer
SQL
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; -- suppose an application check now discovers account 2 was closed -- and the credit should never happen: ROLLBACK; -- the debit above never happened either — balance for account 1 -- is exactly what it was before BEGIN
This is the entire point of grouping statements into a transaction: the debit alone is never visible to anyone else, and it is completely reversed the moment you roll back.
A safer worked example
In practice, application code typically runs the statements, checks for errors, and then decides which of the two to issue:
Pseudocode around the transaction
SQL
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; -- if both statements succeeded and balance checks pass: COMMIT; -- if anything failed along the way: ROLLBACK;
Autocommit mode
Many database clients and drivers run in autocommit mode by default: each individual statement is automatically wrapped in its own implicit transaction and committed the instant it finishes, unless you explicitly start a transaction with
BEGIN. This is convenient for one-off statements, but it means that without an explicit BEGIN, there is no multi-statement grouping to roll back. Check how your specific database driver or tool behaves — the exact default varies.A dropped connection mid-transaction
If a connection is lost after
BEGIN but before COMMIT, most databases automatically roll back the open transaction. This is a safety net, not a substitute for explicit ROLLBACK calls in your application's error handling — always handle failure paths deliberately rather than relying on the connection dropping.