Row and table locks
Overview and setup
Locks coordinate access to shared resources. A row lock can prevent competing writes or incompatible row locks on a selected row; a table lock controls operations on the table as a whole. PostgreSQL takes table locks automatically even for ordinary queries. Row locks generally do not prevent ordinary snapshot reads. A table lock named ROW EXCLUSIVE is still a table-level lock.
Use a fresh disposable file database initialized with versions/v56/locking-fixture.sql. Enable WAL with PRAGMA journal_mode=WAL; before opening two independent private-cache connections A and B. Use driver autocommit, no implicit transaction, zero busy timeout, and fully fetch each query result. Follow steps in order; the included Python validator automates this. Never use production data.
First two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session A
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=2;Observed error: SQLITE_BUSY
4. Session A
COMMIT;5. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=2;6. Session B
SELECT id,qty,version FROM lock_item ORDER BY id;Observed rows: [[1, 11, 2], [2, 21, 2]]
How it works
SQLite WAL permits concurrent readers but serializes writers across the database. A holds a write transaction; B cannot write even to item 2, then succeeds after A commits. The second schedule shows B reading the old committed quantity while A writes. This is not PostgreSQL row locking. Keep transactions short and do not hold locks during user input or remote calls. See the PostgreSQL schedule file for a contrast.
Second two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session A
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session B
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[10, 1]]
4. Session A
COMMIT;5. Session B
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[11, 2]]
Practice and mistakes
Practice: replace A’s commit with rollback in example 1; predict final quantities. Hint 1: only A’s changes are discarded. Hint 2: B retries after release. Mistake: assuming different rows imply independent SQLite writers.