Sub topic 13
Transactions and ACID guarantees
This chapter assumes you can write basic INSERT, UPDATE, and SELECT statements. It also assumes you know what primary keys, foreign keys, and CHECK constraints do. Constraints reject a single bad row. Transactions protect a group of statements that must succeed or fail together.
Why single statements are not enough
Moving 100 from account 1 to account 2 takes two updates: one subtracts and one adds. Suppose the server crashes between them. The money has left account 1 and never arrived in account 2. No constraint is violated, because each row is valid on its own. The data is still wrong.
A transaction is a group of SQL statements that the database treats as one unit of work. The database promises that the group either takes full effect or has no effect. Other sessions also cannot see the group half-finished.
The basic commands
The examples use this table. Run it in PostgreSQL, MySQL (InnoDB), or SQLite.
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
owner VARCHAR(100) NOT NULL,
balance DECIMAL(10, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (account_id, owner, balance) VALUES (1, 'Ada', 500.00);
INSERT INTO accounts (account_id, owner, balance) VALUES (2, 'Grace', 50.00);A transfer wraps both updates:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;BEGINstarts a transaction.START TRANSACTIONis the standard spelling, and MySQL and PostgreSQL accept both.COMMITmakes every change permanent and visible to other sessions.ROLLBACKdiscards every change made sinceBEGIN.
Autocommit
Without an explicit BEGIN, most databases run each statement in its own transaction and commit it immediately. This is called autocommit. Every statement is atomic by itself, but two statements are not atomic together. Multi-statement work needs an explicit BEGIN.
ACID
ACID names four guarantees that a transactional database provides.
| Letter | Property | Protects against |
|---|---|---|
| A | Atomicity | A transaction applying only partly |
| C | Consistency | A transaction leaving data that breaks the rules |
| I | Isolation | Concurrent transactions interfering with each other |
| D | Durability | Committed data being lost after a crash |
Atomicity: all or nothing
Atomicity means a transaction is indivisible. If any statement fails, you roll back, and the database returns to the state before BEGIN.
Try transferring 1000 from Grace, who holds 50:
BEGIN;
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 1;
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 2;
ROLLBACK;The second update would violate CHECK (balance >= 0), so the database raises an error. The first update has already run inside the transaction. Rolling back removes it, so Ada's balance is unchanged. Without the transaction, Ada would keep 1000 that never left Grace.
What happens after an error depends on the database. In PostgreSQL, an error puts the whole transaction into an aborted state, and every later statement fails until you issue ROLLBACK. In MySQL and SQLite, the failed statement is undone but the transaction stays open, so your code must still decide whether to continue or roll back. In every case, application code should roll back when a statement fails.
Consistency: valid state to valid state
Consistency means a committed transaction moves the database from one valid state to another. Valid means every constraint holds: primary keys, foreign keys, NOT NULL, UNIQUE, and CHECK. The database enforces the rules you declared, and nothing more.
The database does not know that money must be conserved in a transfer. If you wrote the second update with a wrong amount, every constraint would still pass and the data would be wrong. Business rules that are not expressed as constraints are the application's responsibility. This is why "C" is the least mechanical letter of ACID: it depends on both the database and your schema design.
Isolation: concurrent sessions
Real databases serve many sessions at once. Isolation means each transaction behaves as if it had the database to itself, even when others run at the same time. Perfect isolation costs performance, so databases offer levels that trade protection for concurrency.
Three problems appear when isolation is weak:
- A dirty read sees changes another transaction has not committed yet. If that transaction rolls back, you acted on data that never existed.
- A non-repeatable read happens when you read the same row twice in one transaction and get different values, because another transaction committed a change in between.
- A phantom read happens when you run the same query twice and the second run returns extra or missing rows, because another transaction inserted or deleted matching rows.
The SQL standard defines four isolation levels by which of these they allow.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented |
The table shows the standard's minimum rules. Real systems differ. PostgreSQL's REPEATABLE READ also prevents phantoms, and PostgreSQL treats READ UNCOMMITTED as READ COMMITTED. The defaults also differ:
| Database | Default isolation level |
|---|---|
| PostgreSQL | READ COMMITTED |
| MySQL (InnoDB) | REPEATABLE READ |
| SQLite | SERIALIZABLE (one writer at a time) |
You choose a level for a transaction like this (PostgreSQL syntax shown; MySQL uses SET TRANSACTION ISOLATION LEVEL ... before START TRANSACTION):
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT balance FROM accounts WHERE account_id = 1;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
COMMIT;At SERIALIZABLE, the database may abort a transaction with a serialization failure to keep results equal to some one-at-a-time order. Your application must be ready to retry the whole transaction.
The lost update
A common concurrency bug is the lost update. Two sessions both read a balance of 500, and each computes a new value in application code.
- Session A reads 500 and plans to write 400.
- Session B reads 500 and plans to write 450.
- A writes 400 and commits.
- B writes 450 and commits. A's change is gone.
Two fixes are common. The first is to let the database do the arithmetic in one statement, as the transfer above does with balance = balance - 100. The second is to lock the row while you work on it:
BEGIN;
SELECT balance FROM accounts WHERE account_id = 1 FOR UPDATE;
-- application checks the balance and decides what to do
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
COMMIT;FOR UPDATE makes other transactions that try to lock or change that row wait until you finish. PostgreSQL and MySQL support it. SQLite does not need it, because it allows only one writer at a time.
Durability: surviving a crash
Durability means that once COMMIT returns successfully, the data survives a power failure or crash. Most databases do this with a write-ahead log (WAL). Before changing the data files, the database writes a record of the change to a sequential log and forces it to disk. After a crash, it replays the log to recover committed work and discards work that never committed.
Durability is only as strong as the storage. Some systems can be configured to acknowledge a commit before the log reaches disk, for example PostgreSQL's synchronous_commit = off. This is faster and risks losing the most recent commits in a crash. Disks and caches that lie about flushing can also break the promise.
Common errors
- Forgetting to commit. Changes made in an open transaction are invisible to other sessions. Closing the connection usually rolls them back.
- Holding a transaction open too long. Open transactions hold locks and prevent cleanup of old row versions. Do not wait for user input or call slow external services inside a transaction.
- Not handling failure. If the code does not issue
ROLLBACKafter an error, the connection can be left in an aborted or half-finished transaction. Use your driver's pattern of commit on success and rollback in an error handler. - Reading, deciding, then writing. Checking a value in one statement and acting on it in another is vulnerable to lost updates. Use a single atomic statement, a lock, or a higher isolation level.
- Assuming defaults are portable. The same code can behave differently on PostgreSQL and MySQL because their default isolation levels differ.
- Skipping retries. At higher isolation levels, deadlocks and serialization failures are normal events. The application should retry the whole transaction.
Summary
A transaction groups statements so they take effect together. Atomicity makes the group all-or-nothing. Consistency means constraints hold after every commit. Isolation limits what concurrent sessions can see of each other. Durability keeps committed data through crashes. Higher isolation costs concurrency, so pick the level your correctness needs, and write code that rolls back on errors and retries when the database asks.
Exercise
Two sessions each read an account balance of 500 in separate transactions at READ COMMITTED. Session A subtracts 100 in application code and writes 400. Session B then subtracts 50 in application code from its own read and writes 450. Both commit. What is the final balance, which problem is this, and name two ways to prevent it.
Show answer
The final balance is 450, but the correct result is 350. This is a lost update, because B overwrote A's change using a stale read. Two fixes: use one atomic statement such as UPDATE accounts SET balance = balance - 50 WHERE account_id = 1, or lock the row with SELECT ... FOR UPDATE before computing the new value. Running at SERIALIZABLE and retrying on a serialization failure would also work.
Exercise
A transfer runs two UPDATE statements without BEGIN, on a database in autocommit mode, and the server crashes after the first statement returns. What is the state of the data after restart, and which ACID property would have prevented it?
Show answer
The first update was committed on its own and survives the crash, because durability applies to it. The second update never ran. Money has left one account without arriving in the other. Atomicity, obtained by wrapping both updates in BEGIN ... COMMIT, would have prevented this, because the database would roll back an uncommitted transaction during crash recovery.