← Back to SQL, page 12

sql-0228 · Medium mid

Two connections try to write to the same SQLite database at the same time. What happens to the second one?

SQLite allows one writer at a time for the whole database. While A holds the write lock, B's write fails with 'database is locked' (SQLITE_BUSY), unless B has a busy timeout, in which case it waits and retries until A finishes or the timeout expires. Applications should set a busy timeout and keep write transactions short.

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 purpose
text
Error: database is locked

The 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;
idbalance
190
260

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