"database is locked" is SQLite’s error for a concurrency conflict: another connection holds a lock that your statement needs. In normal non-shared-cache mode, SQLite coordinates writes across the database rather than through row or table locks, so only one write transaction can run at a time. The error is SQLITE_BUSY (code 5), and it is retryable: the lock clears once the other connection commits or rolls back.
SQLite’s WAL (write-ahead logging) mode appends changes to a separate file instead of rewriting the database in place, so readers and writers no longer block each other and the most common cause of the error disappears. The one-writer rule remains, though, so two writers can still collide, and you can reproduce that conflict. A busy timeout (a wait-and-retry setting) fixes some cases but not others. Checkpointing and long readers also create the error, and a retryable lock is not the same as corruption or a filesystem limitation.
What the two SQLite lock errors mean
SQLite reports two lock errors. SQLITE_BUSY (code 5) means an operation conflicts with a separate connection. In normal non-shared-cache mode, only one write transaction can run on the database at a time. SQLITE_LOCKED (code 6) means a conflict within the same connection or with another connection using a shared cache. Check active statements on the connection and whether shared-cache mode is enabled.
SQLITE_BUSY is a conflict between connections. The database file is intact; another connection is holding a lock. The standard fix is to wait and retry, and deleting files to "unlock" the database is dangerous.
Why WAL mode removes most reader/writer blocking
WAL (write-ahead logging) mode changes how SQLite writes: instead of modifying the main database file in place, SQLite appends changes to a separate -wal file (the write-ahead log), and a checkpoint operation later copies those changes back into the main file. In WAL mode, readers and writers no longer block each other, which removes the most common cause of busy errors in workloads that read and write at the same time. In the default rollback-journal mode, SQLite’s original write strategy, a reader merely holding a read transaction open blocks a writer’s commit; switching to WAL mode fixes that sequence.
WAL mode is a persistent property of the database file: set it once and every future connection gets it. But WAL still allows only one writer at a time, so two concurrent writers can still collide. Keep the busy timeout even after enabling WAL.
Reproduce the writer conflict
A minimal Python script shows the failure and the fix: it opens two connections to the same WAL-mode database. Connection A starts a write transaction and holds it for two seconds while connection B tries to write.
import sqlite3
import threading
import time
DB = "locked_example.db"
def connect():
conn = sqlite3.connect(DB, timeout=0, isolation_level=None) # autocommit; manage transactions manually
conn.execute("PRAGMA busy_timeout = 5000")
return conn
setup = connect()
setup.execute("PRAGMA journal_mode=WAL")
setup.execute("CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, value TEXT)")
setup.close()
def writer_a():
conn = connect()
conn.execute("BEGIN IMMEDIATE")
conn.execute("INSERT INTO items (value) VALUES ('from A')")
time.sleep(2)
conn.commit()
conn.close()
def writer_b():
conn = connect()
start = time.time()
conn.execute("BEGIN IMMEDIATE")
conn.execute("INSERT INTO items (value) VALUES ('from B')")
conn.commit()
print(f"B waited {time.time() - start:.1f}s, then committed")
conn.close()
threading.Thread(target=writer_a).start()
time.sleep(0.5)
writer_b()
With the busy_timeout line in place, B waits for A’s transaction to finish and then commits. Remove that line and B fails immediately at BEGIN IMMEDIATE with sqlite3.OperationalError: database is locked.
Fix the writer conflict
The first fix is a busy timeout. SQLite’s default C-level busy handler is unset, but Python’s sqlite3.connect defaults to a five-second timeout. The example sets timeout=0 explicitly so removing its pragma demonstrates immediate failure. PRAGMA busy_timeout = 5000 makes a blocked statement retry until the lock frees or the timeout elapses. The setting is per connection, so it belongs in the code that opens connections, not in a one-off console session. A busy timeout handles short waits, but a transaction held open for minutes will still time out everyone else.
The second fix is to take the write lock early. A plain BEGIN starts a transaction without taking the write lock; the lock is acquired at the first write statement. If that statement is the tenth statement in a batch, the connection has already done work that will be wasted when the lock fails. BEGIN IMMEDIATE claims the write lock at the start, so the conflict appears at the very first statement, where retrying is trivial. Use BEGIN IMMEDIATE whenever the transaction will write.
There is one case where a busy timeout does not help. A connection that begins with a read and then tries to write must upgrade its read lock to a write lock, and that upgrade uses a non-blocking lock. If another writer holds the lock at that moment, the upgrade fails immediately with SQLITE_BUSY, even on builds that use operating-system blocking locks (the SQLITE_ENABLE_SETLK_TIMEOUT option). BEGIN IMMEDIATE avoids the upgrade by taking the write lock before any read.
The third fix is to keep write transactions short. SQLite does not support concurrent write transactions, and long transactions that include a write will cause problems. Commit or rollback promptly, and do not hold a write transaction open across slow operations such as network calls or user input.
When the error persists despite a busy timeout, look for the other connection. PRAGMA lock_status reports only the calling connection’s locks, so it will not name the culprit. On macOS and Linux, lsof lists every process holding the database file, which is the fastest way to discover a command-line session you left open or a second app instance.
Checkpointing and long readers
In WAL mode, a long-running read transaction (a transaction that only reads data) can stall a FULL, RESTART, or TRUNCATE checkpoint, and it does not block writers. A checkpoint copies committed frames from the -wal file back into the main database file. The sqlite3_wal_checkpoint_v2 interface runs a checkpoint. In PASSIVE mode, SQLite copies frames without waiting for readers or writers, and the busy timeout handler is never invoked. In FULL mode, SQLite blocks until there is no writer and all readers are reading from the most recent database snapshot. RESTART and TRUNCATE checkpoints take exclusive read-mark locks, which is why a long reader can stall them.
A long-running read transaction makes the WAL file grow because the checkpoint cannot advance past the reader’s snapshot. If the WAL file grows without limit, look for a connection that opened a read transaction and never closed it. Use PASSIVE checkpoints for routine maintenance, and schedule FULL checkpoints for quiet periods.
A checkpoint can also produce "database is locked" by itself. Every checkpoint call takes an exclusive checkpoint lock; if another process is already running a checkpoint, the call returns SQLITE_BUSY and the busy timeout handler is not invoked in that case. And PRAGMA main.wal_checkpoint(RESTART) is a one-time operation, not a configuration setting, so regular checkpoints need to be scheduled from your own code.
When the error is not a lock
A retryable lock is not the same as corruption. SQLITE_BUSY means another connection holds a lock and the data is intact. Corruption produces different errors, and the fastest way to turn a lock problem into corruption is to delete the -wal or -journal files to "unlock" the database: deleting either one can corrupt the database or silently discard committed data. If you suspect corruption, run PRAGMA integrity_check rather than deleting files.
WAL mode also depends on the filesystem. It needs a shared-memory file (-shm) and file-locking features that not every filesystem provides. The locking design assumes read/write clients can use blocking locks on the -shm file; read-only -shm clients never use blocking locks. On filesystems that do not support these features, such as some network filesystems, WAL can fail with errors that look like lock problems. WAL requires processes using the database to run on the same host and does not support access over a network filesystem. If the error appears only on a network mount, test the same workload on a local disk before changing your transaction code.
One more possible cause to check: two different SQLite library instances in the same app. A forum report traced WAL data loss to two SQLite libraries in one app, a Lua binding and a C++ library, which interfered with WAL file handling. If your app links SQLite more than once, use one library instance.
Key takeaways for SQLite lock errors
- SQLITE_BUSY is a retryable concurrency conflict, not corruption: another connection’s transaction can prevent a write. Normal non-shared-cache mode allows one write transaction at a time. Set a per-connection busy timeout and retry; never delete the -wal or -journal files to "unlock" the database.
- WAL mode removes reader/writer blocking but keeps the one-writer rule: two concurrent writers can still collide, so keep PRAGMA busy_timeout even after switching to WAL.
- Claim the write lock early with BEGIN IMMEDIATE: the conflict appears at the first statement, where retrying is trivial. The read-to-write upgrade that can fail despite a busy timeout never happens.
- Keep write transactions short: a transaction held open for minutes makes every other writer time out; commit or rollback promptly.
- Long readers stall checkpoints, not writers: a checkpoint cannot advance past a reader’s snapshot, so the WAL file grows; use PASSIVE checkpoints for routine maintenance and schedule FULL checkpoints for quiet periods.