Sub topic 3
Atomicity: all or nothing
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), what a primary key and a CHECK constraint are, and the basic BEGIN, COMMIT and ROLLBACK commands from the previous chapter. The examples use PostgreSQL syntax. Where other systems behave differently, the text says so.
What atomicity guarantees
Atomicity means a transaction is the smallest unit of change the database will apply. Either every statement in the transaction takes effect, or none of them does. No other session will ever see a state in which only some of the statements ran, and after a failure the database will not keep half of a transaction.
The name comes from the Greek word for "indivisible". The transaction may contain many statements, but the database treats it as one operation.
Atomicity is about outcomes, not timing. Statements still run one after another inside the transaction. What the guarantee covers is the result:
- If the transaction commits, all of its changes become permanent and visible together.
- If the transaction rolls back, all of its changes are discarded.
- If the session, the server or the machine fails before
COMMITcompletes, the database treats the transaction as rolled back.
A transfer that must not be split
A money transfer is the standard example because it needs two writes that only make sense together. Taking 30 from one account without adding 30 to the other would destroy money. Adding without taking would create it.
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);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;Between the two UPDATE statements, the table inside your own session holds an in-between state: account 1 has 70.00 and account 2 still has 50.00. Atomicity guarantees that other sessions never observe that state. They see 100.00 and 50.00 before the commit, and 70.00 and 80.00 after it.
Without BEGIN, most clients run in autocommit mode, where each statement is its own transaction. Each UPDATE would then be atomic on its own, but the pair would not be. A crash between them would leave the transfer half done.
How a failure triggers a rollback
A transaction can end without a commit for three reasons:
- You issue
ROLLBACK. - A statement fails, for example because a constraint is violated, and your code decides to abort.
- The connection or server dies before
COMMIT.
The second case is the one that matters most in practice:
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 CHECK constraint stops the invalid row from being written. Rolling back then undoes anything else the transaction did before the failure. If this had been the second statement of a transfer, the first statement's debit would also disappear.
The aborted-transaction state in PostgreSQL
In PostgreSQL, once a statement fails inside a transaction, the whole transaction enters an aborted state. Every further statement is refused with the error current transaction is aborted, commands ignored until end of transaction block. The only useful commands are ROLLBACK and ROLLBACK TO SAVEPOINT. Even if you send COMMIT, PostgreSQL performs a rollback and reports ROLLBACK.
This is deliberate. It prevents code from ignoring an error and committing a partial result by accident.
Other systems differ:
| System | Behavior after a failed statement |
|---|---|
| PostgreSQL | The whole transaction is aborted. Only rollback is accepted. |
| MySQL (InnoDB) | Only the failing statement is rolled back by default. The transaction stays open, and a later `COMMIT` keeps the earlier statements. |
| SQL Server | Depends on the `XACT_ABORT` setting. With it off, many errors roll back only the statement. |
| Oracle | Only the failing statement is rolled back. The transaction stays open. |
If you write portable code, always check for errors and issue an explicit ROLLBACK yourself. Do not rely on the database to clean up for you.
Statement-level atomicity
Atomicity also applies below the transaction level. A single UPDATE that touches 1,000 rows is atomic. If row 700 violates a constraint, the statement fails and the changes to rows 1 to 699 are undone. This holds even in autocommit mode, and it is why one multi-row statement is safer than a loop of single-row statements outside a transaction.
Partial rollback with savepoints
Sometimes you want to undo only part of a transaction. A savepoint marks a position inside the transaction that you can return to.
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.ROLLBACK TO SAVEPOINT undoes everything done after the savepoint, but the transaction remains open and the earlier work is kept. The savepoint itself also stays defined, so you can roll back to it again. RELEASE SAVEPOINT before_bonus removes the marker without undoing anything.
Savepoints also rescue a PostgreSQL transaction from the aborted state. If a statement fails after you created a savepoint, ROLLBACK TO SAVEPOINT clears the error and lets the transaction continue. Application drivers use this to implement "try this statement, and carry on if it fails" inside a larger transaction.
Savepoints do not change the atomicity guarantee. The transaction as a whole is still all or nothing. A savepoint only lets the transaction decide what "all" means before it commits.
The mechanism behind atomicity
The database must be able to undo changes, both when you ask for it and after a crash. Two designs are common:
- Undo log. The database writes changes in place and keeps a record of the old values. Rollback applies the undo records in reverse. Oracle and MySQL InnoDB work this way.
- Multiversion storage. The database never overwrites a row. An
UPDATEcreates a new row version and marks the old one as replaced. Each version records which transaction created it. If that transaction rolls back, its versions are simply never treated as visible. PostgreSQL works this way.
In PostgreSQL, a rollback is therefore cheap. The database records that the transaction aborted, and the rows it wrote become dead versions that vacuum removes later. A commit is also cheap, because it is mostly one status flag plus a log flush. In an undo-log system, commit is cheap and rollback of a large transaction can be slow, because the work must be reversed.
For crashes, the database combines these ideas with a write-ahead log, which a later chapter covers. For now, remember the rule that it enforces: a transaction counts as committed only if its commit record is safely recorded. After a crash, any transaction without a commit record is treated as rolled back.
What atomicity does not cover
Atomicity is easy to over-trust. It does not provide the following:
- Isolation. Atomicity says nothing about what other sessions see while your transaction is open, apart from the rule that they never see a partial commit. Whether they can read your uncommitted changes, or whether your reads stay stable, is decided by isolation, covered in later chapters.
- Side effects outside the database. If your code sends an email or calls a payment API inside a transaction and the transaction then rolls back, the database cannot unsend the message. Do external actions after the commit succeeds, or record them in a table inside the same transaction and perform them from there.
- Sequences and similar objects. In PostgreSQL, a value taken from a sequence is not returned on rollback. A rolled-back insert can leave a gap in an auto-increment column. This is expected behavior.
- Schema changes in every system. PostgreSQL allows most DDL (
CREATE TABLE,ALTER TABLE) inside a transaction and rolls it back. MySQL and Oracle commit implicitly when they see DDL, which ends your transaction early. - Transactions across several databases. One database can make its own changes atomic. Making changes in two separate systems atomic needs extra coordination, covered at the end of this tutorial.
Common mistakes
- Forgetting
BEGINin a multi-statement change. In autocommit mode each statement commits at once, so a failure partway leaves a half-finished change. - Swallowing errors. Catching an exception in application code and continuing leads to either an aborted-transaction error (PostgreSQL) or a partial commit (other systems).
- Leaving a transaction open. A session that runs
BEGINand then waits for user input or a slow network call holds its changes and locks. Keep transactions short. - Assuming a connection drop is a commit. If the connection fails while
COMMITis in flight, the client cannot know the outcome. The commit may have succeeded on the server before the reply was lost. Check the state before you retry.
A complete example in application code
The following Python script uses the psycopg driver (version 3). It runs the transfer as one transaction and rolls back if anything fails. The connection context manager commits on normal exit and rolls back if an exception escapes.
import psycopg
def transfer(conninfo: str, src: int, dst: int, amount: str) -> None:
with psycopg.connect(conninfo) as conn:
with conn.cursor() as cur:
cur.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, src),
)
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
# Leaving the "with conn" block commits.
# An exception, such as a CHECK violation, rolls back instead.
if __name__ == "__main__":
try:
transfer("dbname=bank", 1, 2, "500")
except psycopg.errors.CheckViolation:
print("Transfer rejected: insufficient funds. Nothing was changed.")If the debit violates the CHECK constraint, the exception leaves the with block, the driver rolls back, and the script reports a clean failure. Account 2 is never credited.
Exercise
A transaction in PostgreSQL runs UPDATE a, then UPDATE b, and the second statement fails with a constraint error. The application ignores the error and sends UPDATE c, then COMMIT. What happens to a, b and c? How would the result differ in MySQL (InnoDB) with default settings?
Show answer
In PostgreSQL the transaction is aborted after the failure. UPDATE c is refused, and COMMIT is turned into a rollback, so none of a, b or c is applied. In MySQL (InnoDB) only the failing statement is rolled back and the transaction stays open. UPDATE c runs and COMMIT makes a and c permanent while b is missing, which is a partial result that the application caused by ignoring the error.
Exercise
You run a transaction with BEGIN, UPDATE accounts SET balance = balance - 10 WHERE id = 1, SAVEPOINT s, UPDATE accounts SET balance = balance - 20 WHERE id = 1, ROLLBACK TO SAVEPOINT s, COMMIT. By how much does the balance of account 1 change?
Show answer
It decreases by 10. The rollback to the savepoint undoes only the second update. The first update is kept and committed.