Transactions: COMMIT, ROLLBACK, Savepoints and ACID
How transactions group statements into all-or-nothing units: BEGIN, COMMIT and ROLLBACK, the ACID properties, autocommit, what happens when a statement fails (and how databases differ), savepoints, transactions in application code, and keeping transactions short.
kvi5hnuCode Sprout team member9 min readOn this page
Moving money from one account to another takes two updates: subtract from one balance and add to the other. If the system crashes, or the second update fails, between the two, money disappears or appears from nowhere. A transaction prevents that: it groups statements into a single unit that either happens completely or not at all.
Transactions are what make databases trustworthy. This article covers how to use them, what guarantees they give, how errors inside them behave in different databases, savepoints, and how to use them well from application code. Article 61 covers what happens when transactions run at the same time.
The examples use a small accounts table, where Asha has 500.00 and Ben 100.00, and a CHECK constraint forbids negative balances:
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
BEGIN, COMMIT and ROLLBACK
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- A transfer: two updates that must both happen, or neither
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 200 WHERE account_id = 2;
COMMIT;
SELECT account_id, owner, balance FROM accounts ORDER BY account_id;
-- Changed our mind: ROLLBACK undoes everything since BEGIN
BEGIN;
UPDATE accounts SET balance = 0 WHERE account_id = 1;
SELECT balance AS inside_transaction FROM accounts WHERE account_id = 1;
ROLLBACK;
SELECT balance AS after_rollback FROM accounts WHERE account_id = 1;
account_id | owner | balance
------------+-------+---------
1 | Asha | 300.00
2 | Ben | 300.00
(2 rows)
inside_transaction
--------------------
0.00
(1 row)
after_rollback
----------------
300.00
(1 row)
BEGIN(or the standardSTART TRANSACTION) starts a transaction.- The statements that follow are part of it. Their changes are visible inside the transaction, as the query showing a balance of 0.00 proves, but not yet to other sessions.
COMMITmakes all the changes permanent and visible to everyone, at once.ROLLBACKundoes every change sinceBEGIN. Asha's balance is back to 300.00.
The first transfer moved 200.00 from Asha to Ben as a unit: no other session could ever see the money gone from Asha's account but not yet in Ben's.
ACID
Transactions give four guarantees, known as ACID:
| Property | Meaning | In the examples |
|---|---|---|
| Atomicity | all of a transaction's changes happen, or none | the transfer's two updates commit together, or roll back together |
| Consistency | a transaction takes the database from one valid state to another, respecting every constraint | a transfer that would leave a negative balance is refused |
| Isolation | concurrent transactions don't see each other's unfinished work | other sessions never see the money in transit (article 61) |
| Durability | once COMMIT returns, the changes survive crashes and power failures | the database writes the change to its log on disk before confirming |
Durability works through the write-ahead log (WAL, or redo log): every change is recorded in a sequential log file, and flushed to disk at commit, before the data files themselves are updated. After a crash, the database replays the log to recover committed work and discards uncommitted work. PostgreSQL's synchronous_commit = off trades a small window of possible loss of the most recent commits for faster commits, which some applications accept for non-critical data.
When a statement fails inside a transaction
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- Asha (500.00) sends 600.00 to Ben (100.00): the credit works, the debit breaks the CHECK
BEGIN;
UPDATE accounts SET balance = balance + 600 WHERE account_id = 2; -- succeeds
UPDATE accounts SET balance = balance - 600 WHERE account_id = 1; -- would leave -100.00
SELECT balance FROM accounts WHERE account_id = 2; -- refused: the transaction has failed
COMMIT; -- becomes a rollback
-- Ben's credit was undone too: no money was created
SELECT account_id, owner, balance FROM accounts ORDER BY account_id;
psql:/workspace/solution.sql:11: ERROR: new row for relation "accounts" violates check constraint "accounts_balance_check"
DETAIL: Failing row contains (1, Asha, -100.00).
psql:/workspace/solution.sql:12: ERROR: current transaction is aborted, commands ignored until end of transaction block
account_id | owner | balance
------------+-------+---------
1 | Asha | 500.00
2 | Ben | 100.00
(2 rows)
Asha tries to send 600.00 with only 500.00. Ben's credit succeeds, then Asha's debit breaks the CHECK constraint. In PostgreSQL, an error puts the whole transaction into an aborted state: every following statement is refused with "current transaction is aborted", and the final COMMIT actually performs a rollback. Ben's credit is undone, and both balances are unchanged. That's atomicity doing its job: the transfer either happens completely or not at all.
Other databases behave differently, and this catches people out when moving between them:
- MySQL, SQL Server and Oracle roll back only the failing statement. The transaction stays open, the earlier credit is still there, and a
COMMITwould commit it: the money would be created from nothing. The application must notice the error and roll back itself. - SQL Server's
SET XACT_ABORT ONmakes most errors roll back the whole transaction, which is the usual recommendation there.
The portable rule: when any statement in a transaction fails, roll back the transaction (or roll back to a savepoint), unless you've deliberately handled that error.
Savepoints
A savepoint marks a point inside a transaction that you can roll back to, without abandoning the whole transaction:

CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- Savepoints: undo part of a transaction and carry on
BEGIN;
INSERT INTO accounts VALUES (3, 'Chen', 50.00);
SAVEPOINT before_fee;
UPDATE accounts SET balance = balance - 80 WHERE account_id = 3; -- an 80.00 fee would overdraw
ROLLBACK TO SAVEPOINT before_fee; -- undo just that, recover
UPDATE accounts SET balance = balance + 25 WHERE account_id = 3;
COMMIT;
SELECT account_id, owner, balance FROM accounts ORDER BY account_id;
psql:/workspace/solution.sql:13: ERROR: new row for relation "accounts" violates check constraint "accounts_balance_check"
DETAIL: Failing row contains (3, Chen, -30.00).
account_id | owner | balance
------------+-------+---------
1 | Asha | 500.00
2 | Ben | 100.00
3 | Chen | 75.00
(3 rows)
SAVEPOINT before_feemarks the point after Chen's account was created.- The 80.00 fee would overdraw the account and fails. In PostgreSQL, the transaction is now aborted.
ROLLBACK TO SAVEPOINT before_feeundoes everything after the savepoint and clears the aborted state, so the transaction can continue.- The 25.00 credit and the
COMMITsucceed. Chen's account exists with 75.00.
Savepoints are useful when a step in a larger job may fail and can be skipped or retried, such as importing many rows where a few are bad. RELEASE SAVEPOINT discards a savepoint that's no longer needed. Savepoints can be nested, and rolling back to an earlier one discards the later ones. Drivers and ORMs use them for "nested transactions". They have a cost, so don't set one per row in a huge loop if you can avoid it.
Autocommit
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner TEXT NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500.00), (2, 'Ben', 100.00);
-- Autocommit: without BEGIN, each statement is its own transaction
UPDATE accounts SET balance = balance - 50 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 50 WHERE account_id = 99; -- no such account: 0 rows, no error!
SELECT SUM(balance) AS total_money FROM accounts; -- 50 has vanished
-- Check the row count, and fail the transfer when the target doesn't exist
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE account_id = 1;
WITH credited AS (
UPDATE accounts SET balance = balance + 50 WHERE account_id = 99 RETURNING 1
)
SELECT CASE WHEN COUNT(*) = 1 THEN 'ok' ELSE 'no such account' END AS result FROM credited;
ROLLBACK;
total_money
-------------
550.00
(1 row)
result
-----------------
no such account
(1 row)
Without BEGIN, most databases and drivers run in autocommit mode: each statement is its own transaction, committed as soon as it finishes. The first statement takes 50.00 from Asha and commits. The second credits account 99, which doesn't exist. That's not an error: an UPDATE that matches no rows simply updates nothing. Total money drops from 600.00 to 550.00.
Two lessons:
- Statements that belong together must be in one transaction, so a failure can undo all of them.
- Check the number of rows affected. An update that should change exactly one row and changes none is a failure, even though the database reports success. The application can check the row count the driver returns, or the SQL can check it, as the second part of the example does with
RETURNING(article 34). On "no such account", the application rolls back.
Oracle is the exception to autocommit: its tools start a transaction implicitly with the first statement, and nothing is committed until you COMMIT. SQL*Plus commits on a normal EXIT by default (EXITCOMMIT), while a dropped connection rolls back. Don't rely on either: always end with an explicit COMMIT or ROLLBACK. Python's DB-API drivers, such as psycopg, also open a transaction implicitly unless autocommit is turned on, so forgetting conn.commit() loses the work.
Transactions in application code
A typical pattern, in Python with psycopg:
with conn.transaction(): # BEGIN
cur.execute("UPDATE accounts SET balance = balance - %s WHERE account_id = %s", (amount, src))
if cur.rowcount != 1:
raise ValueError("no such source account")
cur.execute("UPDATE accounts SET balance = balance + %s WHERE account_id = %s", (amount, dst))
if cur.rowcount != 1:
raise ValueError("no such target account")
# COMMIT if the block finished, ROLLBACK if it raised an exception
Java's JDBC uses conn.setAutoCommit(false), then conn.commit(), with conn.rollback() in a catch block. Spring's @Transactional and similar framework features wrap a method in a transaction the same way. The rules:
- Always end a transaction, with commit or rollback, even when an exception is thrown. A
try/finally,withblock or framework annotation guarantees it. - Keep transactions short. Do the slow work, such as calling other services, sending email or waiting for user input, outside the transaction. An open transaction holds locks that block other sessions (article 61), and in PostgreSQL it stops
VACUUMfrom cleaning up old row versions, so tables bloat. Sessions shown as "idle in transaction" inpg_stat_activityare a common production problem.idle_in_transaction_session_timeoutends them automatically. - Be ready to retry. Some transactions fail because of concurrency, with deadlocks or serialization failures (article 61), and the correct response is to run the whole transaction again.
- Don't use transactions to "reserve" things across user interactions, such as holding a seat while a customer fills in a payment form. Record the reservation as data with an expiry time instead.
DDL is transactional in PostgreSQL and SQL Server, but commits implicitly in MySQL and Oracle (article 53).
Autonomous transactions
Sometimes a change must be kept even if the surrounding transaction rolls back, such as writing an error to a log table just before rolling back. Oracle supports this with autonomous transactions: a procedure declared with PRAGMA AUTONOMOUS_TRANSACTION runs in its own transaction and commits independently. SQL Server can do something similar by writing to a table variable, which a rollback doesn't undo, then inserting it into the log afterwards.
PostgreSQL has no autonomous transactions. The usual workarounds are to log from the application after the rollback, to write the log through a separate connection, for example with the dblink extension, or to use RAISE LOG so the message goes to the server log rather than a table.
What's current
- PostgreSQL 17 added
transaction_timeout, which limits the total duration of a transaction, alongside the olderstatement_timeoutandidle_in_transaction_session_timeout. - PostgreSQL 18 reports write-ahead log I/O in
pg_stat_ioand adds WAL buffer-full counts toEXPLAIN (ANALYZE, WAL), helping to diagnose slow commits. - The SQL standard's
START TRANSACTIONworks in PostgreSQL and MySQL. SQLite and SQL Server useBEGIN TRANSACTION, and Oracle starts transactions implicitly.
Common questions
What happens if my session disconnects in the middle of a transaction? The database rolls it back. Only committed work survives.
Do I need a transaction for a single statement?
No. A single statement is atomic on its own: an UPDATE of a million rows either changes all of them or none. Transactions matter when several statements must succeed or fail together.
Why does PostgreSQL say "current transaction is aborted"? An earlier statement in the transaction failed. Roll back the transaction, or roll back to a savepoint set before the failure.
What's the difference between ROLLBACK and ROLLBACK TO SAVEPOINT?
ROLLBACK ends the transaction and undoes everything. ROLLBACK TO SAVEPOINT undoes only the work after the savepoint and keeps the transaction open.
Why did my changes disappear? Usually the transaction was never committed: the driver opened one implicitly and the program exited, or an error caused a rollback.
Summary
- A transaction groups statements into an all-or-nothing unit:
BEGIN, thenCOMMITorROLLBACK. - ACID: atomicity, consistency, isolation and durability. The write-ahead log provides durability.
- In PostgreSQL, an error aborts the whole transaction. MySQL, SQL Server and Oracle roll back only the failing statement, so the application must roll back itself.
- Savepoints allow partial rollback inside a transaction.
- In autocommit mode, each statement commits on its own. Group related statements, and check affected row counts.
- In application code, always commit or roll back, keep transactions short, and retry on concurrency failures.
Practice questions
Write a transaction that moves 50.00 from account 2 to account 1.
Answer
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE account_id = 2;
UPDATE accounts SET balance = balance + 50 WHERE account_id = 1;
COMMIT;
In application code, also check that each update affected exactly one row, and roll back if not.
In PostgreSQL, a transaction runs an insert that succeeds, an update that fails, and then COMMIT. What's saved?
Answer
Nothing. The failed update aborts the transaction, and COMMIT performs a rollback, undoing the insert too.
The same sequence runs in MySQL. What's saved?
Answer
The insert. MySQL rolls back only the failed statement and leaves the transaction open, so COMMIT commits the insert. The application should have rolled back when the update failed.
A web request opens a transaction, updates a row, then calls a payment service that takes 20 seconds before committing. What problems can this cause?
Answer
The updated row stays locked for 20 seconds, blocking other transactions that need it. In PostgreSQL, the long transaction also holds back VACUUM. Call the payment service outside the transaction, and record its result in a separate, short transaction.
Previous: SQL Injection and Prepared Statements

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.