> 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 %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://amartyushov.gitbook.io/tech/programming-languages/sql/select-for-update.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
