diff --git a/docs/howto/transactions.md b/docs/howto/transactions.md index 9ed61b6a4d..b317917cfd 100644 --- a/docs/howto/transactions.md +++ b/docs/howto/transactions.md @@ -1,6 +1,10 @@ # Using transactions In the code generated by sqlc, the `WithTx` method allows a `Queries` instance to be associated with a transaction. +## Locking Reads in Transactions + +When you query data and then update related data within the same transaction, regular `SELECT` statements may not provide adequate protection against race conditions. For MySQL/InnoDB, using `SELECT ... FOR UPDATE` provides exclusive locks on the selected rows, preventing other transactions from modifying them until your transaction completes. + For example, with the following SQL structure: `schema.sql`: @@ -15,7 +19,8 @@ CREATE TABLE records ( ```sql -- name: GetRecord :one SELECT * FROM records -WHERE id = $1; +WHERE id = $1 +FOR UPDATE; -- name: UpdateRecord :exec UPDATE records SET counter = $2