> For the complete documentation index, see [llms.txt](https://amartyushov.gitbook.io/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amartyushov.gitbook.io/tech/programming-languages/sql/select-for-update.md).

# select for update

```sql
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, <mark style="background-color:orange;">Tx 2 would be added to the queue for processing after Tx 1</mark> 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 <mark style="background-color:orange;">it prevents the</mark> [<mark style="background-color:orange;">thrashing</mark>](https://en.wikipedia.org/wiki/Thrashing_%28computer_science%29) 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).

{% hint style="info" %}
Write (exclusive) lock. Pessimistic locking.
{% endhint %}
