Sub topic 2
Controlling a Transaction with BEGIN, COMMIT and ROLLBACK
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), understand tables, primary keys and constraints, and have a general idea of what concurrent users are. The examples use PostgreSQL syntax. Other databases differ in small ways, and the chapter points those out where they matter.
The three commands
A transaction is a group of statements that the database treats as one unit of work. Three commands control it:
BEGINstarts a transaction.START TRANSACTIONis the standard SQL spelling, and PostgreSQL accepts both.COMMITends the transaction and makes all of its changes permanent and visible to other sessions.ROLLBACKends the transaction and discards every change made sinceBEGIN.
The lifecycle looks like this:
The "Aborted" state is specific to PostgreSQL. It is covered in detail below.
A successful transaction
The examples use this table:
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100.00), (2, 50.00);A transfer of 30 from account 1 to account 2 needs two updates. If only one ran, money would be created or destroyed. Wrapping both in a transaction prevents that:
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;Until COMMIT runs, other sessions do not see either change. After COMMIT, they see both. The session that ran the transaction sees its own uncommitted changes while it is still open.
You can check this with two psql sessions. In session A, run BEGIN and the first UPDATE, then stop. In session B, run SELECT balance FROM accounts WHERE id = 1;. Session B still sees 100.00. Once session A commits, session B sees 70.00.
A failing transaction
ROLLBACK is how you undo work. You can call it deliberately, for example when application logic decides to cancel. The database also forces the issue when a statement fails:
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
-- Fails: new balance would be negative, so the CHECK constraint rejects it.
-- In PostgreSQL the transaction is now aborted and must be rolled back.
ROLLBACK;
SELECT balance FROM accounts WHERE id = 1;
-- Still the value from before the failed transaction.The error message is new row for relation "accounts" violates check constraint "accounts_balance_check". After it, the account balance is unchanged, and so is every other row the transaction touched.
Autocommit: the transaction you did not write
If you run a statement without BEGIN, the database wraps it in its own transaction and commits it immediately. This is called autocommit mode. In PostgreSQL, MySQL and most other systems, each standalone statement is atomic by itself.
This explains a common mistake. Consider two statements sent without BEGIN:
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
-- the application crashes here
UPDATE accounts SET balance = balance + 30 WHERE id = 2;Each statement is its own transaction. The first one is already committed when the crash happens, so 30 has vanished. Autocommit protects single statements only. When two or more statements must succeed or fail together, you must open a transaction explicitly.
What a statement error does to the transaction
Databases handle an error inside an open transaction in different ways, and this is a frequent source of confusion.
| Database | After a statement error inside a transaction |
|---|---|
| PostgreSQL | The whole transaction enters the aborted state. Every later statement fails with `current transaction is aborted, commands ignored until end of transaction block`. Only `ROLLBACK` (or rolling back to a savepoint) is accepted. |
| MySQL (InnoDB) | Only the failed statement is undone. The transaction stays open and you can continue or commit the earlier work. |
| Oracle | Only the failed statement is undone. The transaction stays open. |
| SQL Server | Depends on the `XACT_ABORT` setting. With it off, many errors undo only the statement. With it on, the whole transaction is rolled back. |
In PostgreSQL, running COMMIT on an aborted transaction does not commit anything. The server reports ROLLBACK as the command tag, which tells you the work was discarded. Do not treat a successful return from COMMIT as proof that your changes were saved without checking the tag or the driver's error handling.
To recover from an error inside a PostgreSQL transaction without losing earlier work, use a savepoint. Savepoints are the subject of a later chapter, but a short example shows why they exist:
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
ROLLBACK TO SAVEPOINT before_bonus;
COMMIT;
-- Only the first UPDATE is committed.Rules that apply to most databases
- A transaction belongs to one connection (session). Two connections never share a transaction, even if they come from the same application. Connection pools make this easy to forget: all statements of one transaction must run on the same pooled connection.
- Nested
BEGINdoes not create a nested transaction. In PostgreSQL, a secondBEGINinside a transaction gives the warningthere is already a transaction in progressand changes nothing. Use savepoints for partial rollback. ROLLBACKoutside a transaction is harmless. PostgreSQL warnsthere is no transaction in progress.- When a connection drops before
COMMIT, the server rolls the transaction back. The same happens if the server crashes. Uncommitted work never survives. - Some statements cannot run inside a transaction block in PostgreSQL, for example
CREATE DATABASEandVACUUM. Most DDL such asCREATE TABLEandALTER TABLEcan, and rolls back cleanly. In MySQL and Oracle, DDL statements cause an implicit commit, so you cannot roll them back.
Setting transaction characteristics
BEGIN accepts options that apply to this transaction only:
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT sum(balance) FROM accounts;
COMMIT;READ ONLY makes the database reject any write, which documents your intent and lets the database optimize. The isolation level controls how this transaction sees concurrent changes. It is explained in a later chapter. If you do not name a level, you get the server default, which is READ COMMITTED in PostgreSQL.
Keep transactions short
Open a transaction, do the work, and commit. Between BEGIN and COMMIT the transaction may hold locks on rows it has changed, and it may prevent the database from cleaning up old row versions. A transaction left open while the application waits for a user, a network call or a sleep can block other sessions.
You can find idle open transactions in PostgreSQL:
SELECT pid, state, xact_start, query
FROM pg_stat_activity
WHERE state = 'idle in transaction';A session in state idle in transaction has run BEGIN and is waiting for the next command. If these sessions pile up, check your application for missing COMMIT or ROLLBACK calls. The setting idle_in_transaction_session_timeout makes the server end such sessions after a limit you choose.
Common errors
- Forgetting to commit. The data looks correct in your own session but is invisible to everyone else, and it disappears when the connection closes.
- Continuing after an error in PostgreSQL. The application catches the error, logs it and tries another statement. That statement fails too. The correct handling is to roll back, or to roll back to a savepoint.
- Mixing autocommit and explicit transactions. A statement sent before
BEGINis already committed and cannot be undone by the laterROLLBACK. - Doing slow work inside a transaction. Calling an external service between
BEGINandCOMMITkeeps locks open for as long as the call takes. Do the slow work first, then open the transaction for the database changes. - Assuming the commit succeeded.
COMMITcan fail, for example on a deferred constraint or a serialization failure. Always check for errors on the commit itself, not only on the statements before it.
Exercise
In PostgreSQL you run BEGIN;, then an UPDATE that violates a CHECK constraint, then a second UPDATE on a different row, then COMMIT;. What happens to each statement, and what does the table contain afterwards?
Show answer
The first UPDATE fails with a constraint error and puts the transaction in the aborted state. The second UPDATE is rejected with "current transaction is aborted, commands ignored until end of transaction block", so it does not run. COMMIT on an aborted transaction performs a rollback and reports ROLLBACK. The table is unchanged. In MySQL InnoDB the result would differ: only the failed statement is undone, the second UPDATE would run, and COMMIT would save it.
Exercise
An application sends UPDATE accounts SET balance = balance - 30 WHERE id = 1; and UPDATE accounts SET balance = balance + 30 WHERE id = 2; as two separate statements on an autocommit connection. It crashes between them. What is the state of the data, and what is the fix?
Show answer
The first update was committed on its own, so account 1 is 30 lower and account 2 is unchanged. The money is lost. The fix is to send BEGIN before the first statement and COMMIT after the second, so both changes commit together or neither does.