select for update

BEGIN;        -- transaction starts
SELECT * FROM kv WHERE k = 1 FOR UPDATE;  -- rows are chosen and locked
UPDATE kv SET v = v + 5 WHERE k = 1;  -- update on locked rows happened
COMMIT;  -- transaction commited

If another transaction (let’s call it Tx 2) hit the database attempting to operate on the same row while this transaction (Tx 1) was processing, Tx 2 would be added to the queue for processing after Tx 1 commits, rather than beginning to execute, failing, and having to retry because Tx 1 changed one of the values Tx 2 was accessing while it was processing.

This is useful because it prevents the thrashing and unnecessary transaction retries that would otherwise occur when multiple transactions are attempting to read those same rows. Any time multiple transactions are likely to be working with the same rows at roughly the same time, SELECT FOR UPDATE can be used to increase throughput and decrease tail latency (compared to what you would see without using it).

Write (exclusive) lock. Pessimistic locking.

Last updated