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);Both connections start deferred transactions and read:
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;| balance |
|---|
| 100 |
sql
BEGIN;
SELECT balance FROM accounts WHERE id = 1;| balance |
|---|
| 100 |
A writes and commits. B, still in its old read snapshot, now tries to write:
sql
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;
SELECT balance AS after_a FROM accounts WHERE id = 1;| after_a |
|---|
| 90 |
sql
UPDATE accounts SET balance = balance - 20 WHERE id = 1; -- error on purposetext
Error: database is lockedB cannot upgrade, because its snapshot is older than the latest commit. Waiting would not help; B must roll back and start again.
With BEGIN IMMEDIATE, the transaction that intends to write takes the lock up front, so a second writer is turned away at its own BEGIN, before it has read anything stale:
sql
ROLLBACK;
BEGIN IMMEDIATE;
SELECT 'B holds the write lock' AS b_status;| b_status |
|---|
| B holds the write lock |
sql
BEGIN IMMEDIATE; -- error on purposetext
Error: database is lockedUse BEGIN IMMEDIATE for any transaction that may write, and set a busy timeout so the second one waits at BEGIN rather than failing.
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);
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
-- second session
BEGIN;
SELECT balance FROM accounts WHERE id = 1;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
COMMIT;
SELECT balance AS after_a FROM accounts WHERE id = 1;
-- error on purpose
-- second session
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
-- second session
ROLLBACK;
BEGIN IMMEDIATE;
SELECT 'B holds the write lock' AS b_status;
-- error on purpose
BEGIN IMMEDIATE;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Deferred BEGIN takes no lock until first use
- A reader that later writes can fail if another writer committed
- In WAL mode a stale snapshot cannot be upgraded to a writer
- BEGIN IMMEDIATE takes the write lock up front
Common mistakes
- Using plain BEGIN for read-then-write transactions
- Retrying the failing statement instead of the whole transaction
Follow-ups
- What does BEGIN EXCLUSIVE add?
- How should an app retry SQLITE_BUSY?
Tips
- Explain why waiting does not help the stale snapshot