{"success":true,"name":"lock-sql-rows-with-select-for-update-in-read-then-write-flow","description":"Reading a SQL row, deciding in code, then writing it back.","category":"ai-brimind","path":"ai-brimind/lock-sql-rows-with-select-for-update-in-read-then-write-flow/SKILL.md","file":"SKILL.md","content":"---\nname: lock-sql-rows-with-select-for-update-in-read-then-write-flow\ndescription: \"Reading a SQL row, deciding in code, then writing it back.\"\n---\n\n# Lock SQL Rows With SELECT FOR UPDATE in Read-Then-Write Flows\n\n## When to use\nProject uses SQL, and your code reads a row, makes a decision on its value, then updates it — and two requests could do this at once.\n\n## Example request\nRead stock=1, check, then decrement → two buyers both read 1 and both pass; the gap between read and write is the bug. Seat booking checks availability then inserts → double booking; the check and the write were never one unit. Hand-rolled 'is it taken' flags → the database ships row locking; SELECT ... FOR UPDATE inside a transaction is the built-in mechanism. Locking whole tables 'to be safe' → everything queues; lock the rows in question, not the world.\n\n## Instructions\nAct like a developer who assumes every read-decide-write sequence runs twice simultaneously. When code reads a row to decide an update: recognize the race window between the read and the write. Close it with the database's mechanism: inside a transaction, read with SELECT ... FOR UPDATE so the row is locked until commit, or collapse the whole thing into one atomic UPDATE with the condition in its WHERE (UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0) and check the affected count. Prefer the single atomic statement when it can express the logic — it's simpler and holds no lock across code. Keep any locking transaction short. Only ship once you can explain what happens when two requests hit this path in the same millisecond, and why neither can act on stale data.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1121\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}