Sub topic 1
Transactions and the I in ACID
Prerequisites
This chapter assumes you can write basic SQL (SELECT, INSERT, UPDATE, DELETE), use BEGIN, COMMIT and ROLLBACK, and know that a database serves many clients at the same time. The examples use a table named accounts with columns id and balance.
Transactions and the I in ACID
A transaction groups several statements into one unit of work. COMMIT makes all of them permanent, and ROLLBACK undoes all of them. ACID is a set of four guarantees that a reliable transaction system provides: Atomicity, Consistency, Isolation and Durability. This chapter covers the I, Isolation.
Isolation means that a transaction should not be affected by other transactions running at the same time. Full isolation, as if transactions ran one after another, is costly because the database must make clients wait. Isolation levels let you choose how much interference you accept in exchange for more concurrency.
What goes wrong when transactions run concurrently
When two transactions overlap, their statements interleave. Without enough isolation, one transaction can see another's unfinished work, or see the same row change while it is still running. Each of these problems is called an anomaly. The next two sections show the most common read anomalies.
Dirty reads
A dirty read occurs when a transaction reads data that another transaction wrote but has not committed. If the writer rolls back, the reader has used a value that never officially existed.
-- Session A -- Session B
BEGIN;
UPDATE accounts SET balance = 0
WHERE id = 1;
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- returns 0 only if dirty reads are allowed
ROLLBACK;
COMMIT;Session B read a balance of 0, but that value was rolled back. PostgreSQL never allows dirty reads, but the SQL standard permits them at the lowest isolation level.
Non-repeatable reads
A non-repeatable read occurs when a transaction reads the same row twice and gets different values, because another transaction committed a change between the two reads.
-- Session A -- Session B
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100
BEGIN;
UPDATE accounts SET balance = 50 WHERE id = 1;
COMMIT;
SELECT balance FROM accounts WHERE id = 1; -- returns 50
COMMIT;Session A's two reads disagree within one transaction. PostgreSQL's default level, READ COMMITTED, allows this.
Exercise
Exercise
In the non-repeatable read schedule, Session B runs ROLLBACK instead of COMMIT. What does Session A's second SELECT return?
Show answer
100. The rolled-back update is never visible to Session A, so the balance stays at its original value.