skip to content

BEGIN, COMMIT and ROLLBACK

autocommit, savepoints, idle in transaction, and the aborted transaction that ignores everything you type.

address
everything.transactions.begin_commit_rollback
part
part 11, transactions and isolation
chapter
chapter 2 of 11
reading time
8 min

every statement runs inside a transaction. without BEGIN, each statement is its own (autocommit). BEGIN groups statements until COMMIT keeps them or ROLLBACK drops them, and a SAVEPOINT lets you drop just the last part. after an error the transaction is aborted: it refuses everything until it ends. and a transaction left open doing nothing is idle in transaction, still holding every lock it took.

the picture

you know how a single UPDATE in psql is just done, no COMMIT needed? that's not because it skipped the transaction. it got one of its own, started and committed around it. BEGIN only makes the transaction longer.

think of a shopping cart (a transaction). autocommit is paying for every item at the till as you pick it up. BEGIN is taking a cart: you fill it, then pay for everything (COMMIT) or put everything back (ROLLBACK). a savepoint is a divider on the belt. and an aborted transaction is a cart the till has refused: you can keep handing it items, it won't scan any of them until you take the cart away.

the server keeps track of which of these states every session is in. here's one session going through all of them on a real server, with pg_stat_activity read after each statement:

T1 sendspg_stat_activity.state after
(connected)idle
BEGIN→ BEGINidle in transaction
UPDATE accounts SET balance = balance + 50.00 WHERE id = 1→ UPDATE 1idle in transaction
UPDATE accounts SET balance = balance - 50.00 WHERE id = 3ERROR 23514 new row for relation "accounts" violates check constraint "accounts_balance_check"idle in transaction (aborted)
SELECT balance FROM accounts WHERE id = 1ERROR 25P02 current transaction is aborted, commands ignored until end of transaction block·
COMMIT→ ROLLBACKidle
real output, a postgres 18.6 server · session-states
one session, captured. between statements it's idle in transaction as soon as BEGIN runs, and idle in transaction (aborted) after the error, until the transaction ends. note what COMMIT says back.

autocommit

each statement outside BEGIN gets its own transaction, and its own transaction id if it writes. pg_current_xact_id() asks for the current one (and assigns it):

sqlempty db
SELECT pg_current_xact_id();
SELECT pg_current_xact_id();
BEGIN;
SELECT pg_current_xact_id();
SELECT pg_current_xact_id();
COMMIT;
output, from postgres 18.6
#1 · SELECT 1
pg_current_xact_idxid8
752
(1 row)
#2 · SELECT 1
pg_current_xact_idxid8
753
(1 row)
#3 · BEGIN
#4 · SELECT 1
pg_current_xact_idxid8
754
(1 row)
#5 · SELECT 1
pg_current_xact_idxid8
754
(1 row)
#6 · COMMIT

two statements, two ids. inside BEGIN, two statements, one id. (transaction ids has where those numbers come from, and why a read-only transaction doesn't use one up.)

autocommit is a client thing as much as a server thing. psql sends what you type, so you're in autocommit until you type BEGIN. many drivers start a transaction for you before the first statement: python's psycopg does by default, JDBC doesn't. find out which one yours is, because the next section's problem starts there.

ROLLBACK and savepoints

ROLLBACK undoes the whole transaction. a savepoint marks a point inside it you can go back to without giving up the rest:

sqldb=bank
BEGIN;
UPDATE accounts SET balance = balance - 10.00 WHERE id = 1;
SAVEPOINT before_fee;
UPDATE accounts SET balance = balance - 25.00 WHERE id = 1;
ROLLBACK TO SAVEPOINT before_fee;
UPDATE accounts SET balance = balance + 10.00 WHERE id = 2;
COMMIT;
SELECT id, owner, balance FROM accounts WHERE id IN (1, 2) ORDER BY id;
output, from postgres 18.6
#1 · BEGIN
#2 · UPDATE 1
#3 · SAVEPOINT
#4 · UPDATE 1
#5 · ROLLBACK
#6 · UPDATE 1
#7 · COMMIT
#8 · SELECT 2
idint4ownertextbalancenumeric
1alice90.00
2bob110.00
(2 rows)

the 25.00 fee is gone, the 10.00 transfer is in. rolling back to a savepoint keeps the savepoint, so you can go back to it again; RELEASE SAVEPOINT forgets it. (underneath, each savepoint is a subtransaction with its own xid once it writes. a few are cheap. thousands of them in one transaction are not.)

the aborted transaction

this is the one that confuses everyone the first time. carol has 0.00, and bank's CHECK says a balance can't go below zero:

predict the output
the second UPDATE fails. the app ignores the error and sends a SELECT, then COMMIT. what does COMMIT do?
sql
BEGIN;
UPDATE accounts SET balance = balance + 50.00 WHERE id = 1;  -- UPDATE 1
UPDATE accounts SET balance = balance - 50.00 WHERE id = 3;  -- ERROR 23514
SELECT balance FROM accounts WHERE id = 1;                   -- ?
COMMIT;                                                      -- ?

here it is, run for real. errors=continue makes the page keep sending statements after the error, the way a careless app would:

sqldb=bank
BEGIN;
UPDATE accounts SET balance = balance + 50.00 WHERE id = 1;
UPDATE accounts SET balance = balance - 50.00 WHERE id = 3;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;
SELECT id, owner, balance FROM accounts WHERE id IN (1, 3) ORDER BY id;
output, from postgres 18.6
#1 · BEGIN
#2 · UPDATE 1
#3 · ERROR 23514
ERROR 23514: new row for relation "accounts" violates check constraint "accounts_balance_check"
DETAIL: Failing row contains (3, carol, 0.00, -50.00, EUR, 0, 2023-01-01 09:10:00+00).
#4 · ERROR 25P02
ERROR 25P02: current transaction is aborted, commands ignored until end of transaction block
#5 · ROLLBACK
#6 · SELECT 2
idint4ownertextbalancenumeric
1alice100.00
3carol0.00
(2 rows)

why so strict? because postgres can't know which of your later statements depended on the one that failed. it won't guess. the only ways out are ROLLBACK (or a COMMIT that turns into one), or going back to a savepoint taken before the error:

sqldb=bank
BEGIN;
UPDATE accounts SET balance = balance + 50.00 WHERE id = 1;
SAVEPOINT try_carol;
UPDATE accounts SET balance = balance - 50.00 WHERE id = 3;
ROLLBACK TO SAVEPOINT try_carol;
UPDATE accounts SET balance = balance - 50.00 WHERE id = 4;
COMMIT;
SELECT id, owner, balance FROM accounts WHERE id IN (1, 3, 4) ORDER BY id;
output, from postgres 18.6
#1 · BEGIN
#2 · UPDATE 1
#3 · SAVEPOINT
#4 · ERROR 23514
ERROR 23514: new row for relation "accounts" violates check constraint "accounts_balance_check"
DETAIL: Failing row contains (3, carol, 0.00, -50.00, EUR, 0, 2023-01-01 09:10:00+00).
#5 · ROLLBACK
#6 · UPDATE 1
#7 · COMMIT
#8 · SELECT 3
idint4ownertextbalancenumeric
1alice150.00
3carol0.00
4dave999950.00
(3 rows)

carol couldn't pay, so dave did. the transaction survived the error because it never got past the savepoint. that's exactly what psql's \set ON_ERROR_ROLLBACK on does for you: a hidden savepoint before every statement in a transaction block.

idle in transaction

a transaction that has sent its last statement and is waiting for the app is idle in transaction. it isn't doing anything, and it still holds everything: row locks, its snapshot, its xid. the classic way to get one is an app that BEGINs, updates a row, then calls a slow payment API before it commits.

T1
·
T2
·
1
BEGIN; UPDATE accounts SET balance = balance - 10.00 WHERE id = 1→ UPDATE 1
lock manager
  • T1ExclusiveLockxid 759

T1 opens a transaction and takes 10.00 from alice. then the app goes off to call a payment API, and doesn't come back.

step 1/3
real output, a postgres 18.6 server · idle-in-transaction
T1 updates alice and goes quiet. T2 wants alice's row and waits behind a session that's doing nothing. T1's session has a 2 s idle limit; the server ends it, its transaction rolls back, and T2 goes through. the list on the right is pg_locks: who holds what, who waits.
pg_stat_activity, before T2 arrives
sessiontextstatetextwait_event_typetext
T1idle in transactionClient
T2idleClient
(2 rows)
pg_stat_activity, while T2 waits
sessiontextstatetextwait_event_typetext
T1idle in transactionClient
T2activeLock
(2 rows)
server log, a few seconds later
  1. FATAL: terminating connection due to idle-in-transaction timeout
what the server showed while it happened: pg_stat_activity before T2 arrived, and while T2 waited. a Lock wait behind an idle in transaction session is the pattern to look for.

the fix is to never hold a transaction open across anything slow (network calls, user input, sleeps), and then to make the server enforce it. idle_in_transaction_session_timeout ends a session that sits idle inside a transaction for too long, as above. transaction_timeout pg 17+ caps the whole transaction, busy or idle. the snapshot an idle transaction holds also stops VACUUM from cleaning up after everyone else: the xmin horizon is that half of the story.

keylines

  • every statement is in a transaction. without BEGIN, it's a transaction of one.
  • ROLLBACK drops everything. ROLLBACK TO SAVEPOINT drops only what came after it.
  • after an error, the transaction refuses everything (25P02). COMMIT turns into ROLLBACK.
  • a savepoint taken before the risky statement is the only way to keep going after it fails.
  • idle in transaction holds its locks and its snapshot. never wait on anything slow inside BEGIN.