Full answer
sql
PRAGMA journal_mode = WAL;
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);B starts a read transaction and reads Ana's balance:
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;| balance |
|---|
| 100 |
A updates and commits while B's transaction is still open:
sql
UPDATE accounts SET balance = 60 WHERE id = 1;
SELECT balance AS a_sees FROM accounts WHERE id = 1;| a_sees |
|---|
| 60 |
B still sees 100, because its read transaction pinned a snapshot:
sql
SELECT balance AS b_sees_in_old_txn FROM accounts WHERE id = 1;| b_sees_in_old_txn |
|---|
| 100 |
After B ends its transaction, a new read sees A's change:
sql
COMMIT;
SELECT balance AS b_sees_after FROM accounts WHERE id = 1;| b_sees_after |
|---|
| 60 |
That snapshot behaviour is a simple form of MVCC: different transactions see different committed versions. WAL needs the database on a local file system (shared memory is used for the index), and the WAL file is merged back into the main file at checkpoints.
sql
PRAGMA journal_mode = WAL;
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
-- second session
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = 60 WHERE id = 1;
SELECT balance AS a_sees FROM accounts WHERE id = 1;
-- second session
SELECT balance AS b_sees_in_old_txn FROM accounts WHERE id = 1;
-- second session
COMMIT;
SELECT balance AS b_sees_after FROM accounts WHERE id = 1;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- WAL lets readers and the writer work at the same time
- Readers see a stable snapshot for their whole transaction
- Still one writer at a time
- Checkpoints move WAL content into the main file
Common mistakes
- Expecting WAL to allow multiple concurrent writers
- Keeping long read transactions open and letting the WAL grow
Follow-ups
- What is a checkpoint?
- Why does WAL not work well on network file systems?
Tips
- Show the reader keeping its old snapshot