Sub topic 11
Locking and `SELECT ... FOR UPDATE`
Prerequisites and the locking model
This chapter assumes that you know basic SELECT and UPDATE statements, primary keys, constraints, and the idea that several sessions can use a database at the same time.
A database lock is a control held by a transaction to protect data from conflicting work. When one transaction changes a row, another transaction that wants an incompatible lock may wait until the first transaction commits or rolls back.
Most databases use different lock modes for reads and writes. The exact modes differ between database systems, but the important rule is consistent: a transaction should hold a lock while it checks and changes the data that must remain related.
Protecting a read-then-write operation
Suppose an application withdraws money. It must read the current balance, check that the balance is sufficient, and then subtract the amount. Without a lock, two concurrent withdrawals could both read the same balance and both approve themselves.
SELECT ... FOR UPDATE reads rows and requests an exclusive row lock for the rest of the transaction. A transaction that tries to update or lock the same rows waits.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance)
VALUES (1, 100.00);
BEGIN;
SELECT balance
FROM accounts
WHERE id = 1
FOR UPDATE;
-- Application checks that balance is at least 30.
UPDATE accounts
SET balance = balance - 30
WHERE id = 1;
COMMIT;The lock protects the gap between the SELECT and the UPDATE. It is released when the transaction ends. Keeping the transaction short reduces the time that other sessions must wait.
Waiting, failure, and work queues
By default, a conflicting statement waits. You can choose different behavior when waiting is undesirable:
FOR UPDATE NOWAITfails immediately if another transaction holds a conflicting lock.FOR UPDATE SKIP LOCKEDignores locked rows. This is useful for workers claiming separate jobs from a queue.- A lock timeout can stop a session from waiting indefinitely.
NOWAIT and lock timeouts require application code to handle the resulting error. The application may retry, return a temporary failure, or choose another item.
A lock is not a substitute for a transaction. This sequence is unsafe because the lock ends when the first transaction ends:
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
COMMIT;
-- The protected interval has ended.
UPDATE accounts SET balance = balance - 30 WHERE id = 1;The read and the dependent write must be in the same transaction.
> callout note > Lock only the rows required by the business rule, and commit promptly. Long transactions increase blocking and make deadlocks more likely.
Common errors
A missing or weak WHERE clause can lock or update far more rows than intended. An index on the searched columns can also help the database find the target rows efficiently, although the exact locking behavior depends on the database system and query plan.
Locks can create deadlocks. For example, one transaction locks account 1 and then requests account 2, while another locks account 2 and then requests account 1. Databases usually abort one transaction. Applications should retry the entire transaction when the database reports a deadlock or serialization failure.
Exercise
Why must the balance check and the balance update occur in the same transaction after SELECT ... FOR UPDATE?
Show answer
The row lock lasts only until the transaction commits or rolls back. Keeping both operations together prevents another transaction from changing the row between the check and the update.