Sub topic 1
What a Transaction Is and Why It Exists
Prerequisites
This chapter assumes you already know the following:
- Basic SQL:
SELECT,INSERT,UPDATEandDELETE. - Tables, primary keys and constraints such as
NOT NULLandCHECK. - That several users or processes can talk to one database at the same time.
The examples use PostgreSQL syntax. Most of them run unchanged on other relational databases. Where behavior differs, the text says so.
The problem: one business action, several statements
Most real operations need more than one SQL statement. Moving money between two accounts takes a debit and a credit. Placing an order inserts an order row, several line-item rows, and reduces stock. Each statement is valid on its own, but the business action is only correct when all of them take effect.
Without any grouping, three things can go wrong:
- A failure in the middle. The application crashes, the network drops, or a constraint rejects the second statement. The first statement has already changed the data, so the database now holds a half-finished action. Money has left one account and arrived nowhere.
- Other sessions see the middle. While your two statements run, another session might read the balances. It sees a total that is 30 too low, because the debit is visible and the credit is not yet.
- Concurrent writers collide. Two sessions read the same balance, both compute a new value, and one overwrites the other.
A transaction is a group of SQL statements that the database treats as one unit of work. It exists to solve these three problems. The database promises that the group either takes effect completely or not at all, and that other sessions do not see it half done.
A first transaction
The following script creates a small table and transfers 30 from account 1 to account 2.
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;BEGIN opens the transaction. The two UPDATE statements run inside it. COMMIT ends it and makes both changes permanent and visible to other sessions at the same moment. Other sessions see either balances of 100 and 50, or balances of 70 and 80. They never see 70 and 50.
If something goes wrong before COMMIT, you issue ROLLBACK instead, and the database discards every change made since BEGIN.
The transaction lifecycle
A transaction moves through a small set of states. It starts active, then ends in exactly one of two ways.
Two points about this lifecycle matter in practice:
- The end is final. After
COMMIT, you cannot roll back. To undo a committed change you must run new statements that reverse it. - Errors have a database-specific effect. In PostgreSQL, any error inside a transaction puts it in an aborted state. Every later statement fails with "current transaction is aborted" until you issue
ROLLBACK. Other databases, such as MySQL, may keep the transaction open after a failed statement and let you continue.
Seeing a failure undo work
The CHECK (balance >= 0) constraint stops an overdraft. Inside a transaction, a violation prevents the invalid state from being committed.
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.If the transfer had a successful debit followed by a failing credit, ROLLBACK would also undo the debit. The grouping is what makes the cleanup automatic. You do not write compensating statements by hand.
Autocommit: every statement is already a transaction
If you run a statement without BEGIN, the database does not leave it unfinished. Most databases run in autocommit mode. Each statement is wrapped in its own implicit transaction and committed as soon as it succeeds.
This has a consequence that surprises many people. Two separate statements sent in autocommit mode are two transactions, not one. A crash between them leaves the first committed and the second missing. Grouping statements needs an explicit BEGIN, or a driver setting that turns autocommit off. Check how your client library behaves, because some drivers open a transaction implicitly on the first statement and some do not.
What a transaction promises: ACID
The guarantees a transaction offers are summarized by the acronym ACID. This chapter only names them. Later chapters cover each one and the mechanism behind it.
| Property | Plain meaning | Main mechanism (later chapters) |
|---|---|---|
| Atomicity | All statements take effect, or none do. | Rollback, undo information |
| Consistency | Committed data satisfies the declared rules. | Constraints checked at statement or commit time |
| Isolation | Concurrent transactions do not see each other's partial work. | Locking or multiversion concurrency control |
| Durability | Once committed, data survives crashes. | Write-ahead log |
One caveat is worth knowing early. Consistency is partly the database's job and partly yours. The database enforces the constraints you declare, such as CHECK, foreign keys and unique indexes. It cannot enforce a rule you never expressed. A transaction that debits an account and forgets to credit the other is perfectly valid from the database's point of view.
When to group statements
Use one transaction when several statements must succeed or fail together. These situations are typical:
- Transfers between rows, such as the debit and credit above.
- Parent and child inserts, such as an order and its line items.
- Derived data kept in step, such as inserting a row and updating a counter or summary table.
- Read, decide, then write sequences, where the decision depends on what you read and the data must not change underneath you.
Do not group statements that are logically independent. A transaction holds resources until it ends. Long ones can block other sessions and prevent cleanup of old row versions. A good transaction is as small as correctness allows.
Common mistakes
- Forgetting to end the transaction. A session that runs
BEGINand then idles keeps its locks and snapshot. Always finish withCOMMITorROLLBACK, including on error paths. - Ignoring the aborted state in PostgreSQL. After an error, retrying the next statement in the same transaction will fail. Roll back first.
- Assuming a committed change can be undone.
ROLLBACKonly reaches back to the lastBEGIN. - Treating a read-then-write sequence as safe. Being inside a transaction does not by itself stop another session from changing the row you just read. That depends on the isolation level and locking, covered in later chapters.
Exercise
A script runs UPDATE accounts SET balance = balance - 30 WHERE id = 1; and then UPDATE accounts SET balance = balance + 30 WHERE id = 2; with no BEGIN, on a database in autocommit mode. The process crashes after the first statement finishes. What is the state of the data, and what change fixes the script?
Show answer
The debit is committed and the credit never ran, so 30 has disappeared. In autocommit mode each statement was its own transaction. The fix is to wrap both statements in BEGIN ... COMMIT (or disable autocommit in the driver), so a crash before COMMIT leaves neither change applied.
Exercise
In PostgreSQL, inside an open transaction, an UPDATE violates a CHECK constraint. You then run a valid SELECT in the same transaction. What happens, and what must you do?
Show answer
The SELECT fails with an error saying the current transaction is aborted, because the earlier error put the whole transaction in an aborted state. You must issue ROLLBACK to end it, then start a new transaction if you want to continue.
Exercise
Name two situations where grouping statements into a transaction is the right choice, and one where it is not.
Show answer
Right: a money transfer (debit plus credit), and inserting an order together with its line items. Not right: unrelated statements, or work that includes slow external calls such as an HTTP request, because holding the transaction open blocks other sessions and delays cleanup.