Full answer
sql
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);A begins a write transaction:
sql
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT 'A holds the write lock' AS a_status;| a_status |
|---|
| A holds the write lock |
B tries to write a different row:
sql
UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- error on purposetext
Error: database is lockedThe lock is on the database, not on rows, so even an unrelated row cannot be written. These connections use a timeout of 0 to show the error immediately. With PRAGMA busy_timeout = 5000 (or the driver's timeout option), B would wait up to five seconds for A.
Once A commits, B can write:
sql
COMMIT;
SELECT 'A committed' AS a_status;| a_status |
|---|
| A committed |
sql
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
SELECT id, balance FROM accounts ORDER BY id;| id | balance |
|---|---|
| 1 | 90 |
| 2 | 60 |
This single-writer design is why SQLite suits many readers and modest write rates, and why server engines with row-level locking suit heavy concurrent writes.
sql
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;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SELECT 'A holds the write lock' AS a_status;
-- error on purpose
-- second session
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;
SELECT 'A committed' AS a_status;
-- second session
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
SELECT id, balance FROM accounts ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- SQLite has one writer at a time per database
- A second writer gets SQLITE_BUSY ('database is locked')
- busy_timeout makes it wait and retry
- Keep write transactions short
Common mistakes
- Running with no busy timeout and failing under light concurrency
- Holding write transactions open across slow work
Follow-ups
- How does WAL mode change concurrency?
- What is BEGIN IMMEDIATE for?
Tips
- Mention the busy timeout