Transactions and Consistent Changes
Follow a two-account transfer through commit and reason about failure.
database, sql, postgresql, transaction, consistency, commit, rollbackPreserve a rule across changes
Moving 30 units between two accounts should not change their combined total. This is an invariant: a rule the operation intends to preserve. One statement debits the first account and another credits the second. A transaction provides an atomic boundary for their database changes, but application logic and constraints must still enforce the intended rules.
SQL illustration
Use a fresh PostgreSQL session with no transaction already open. These are fictional integer units, not real financial data:
BEGIN;
CREATE TEMP TABLE accounts (
id integer PRIMARY KEY,
balance integer NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100), (2, 40);
COMMIT;
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
SELECT id, balance FROM accounts ORDER BY id;
COMMIT;
SELECT id, balance FROM accounts ORDER BY id;
Prepared result, both before and after the successful commit:
| id | balance |
|---|---|
| 1 | 70 |
| 2 | 70 |
The initial total is 140. After the debit, the transaction's own view temporarily totals 110; after the credit it totals 140 again. On successful commit, both changes are committed. If an operation fails, report the error and roll back rather than claim success. The example assumes both rows exist and no concurrent changes; real code must verify affected rows and account for concurrent transactions.
See the reasoning
Follow the example one step at a time
Track the transaction's own balances and their total across a successful transfer. This is a prepared teaching demonstration, not live code execution.
Start the transaction
account 1: 100 account 2: 40
total: 140
status: transaction openThe initial combined balance is 140. This example assumes both rows exist and no concurrent changes.
Atomicity is not the whole design
Other transactions do not see uncommitted changes in PostgreSQL. At the
default READ COMMITTED isolation level, an ordinary SELECT sees committed
data as of that query's start as well as its own transaction's earlier changes;
a later query can see other transactions' commits.
Correctness under concurrency may require additional locking, isolation,
retries, and carefully designed checks. CHECK (balance >= 0) does not
by itself ensure that a transfer preserves the combined total, nor does a
transaction undo an external message or payment. Validate failures, use
appropriate permissions, and test recovery separately.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
