Suppose that I am implementing a bank account logic using PostgreSQL. At some point, I will want to check if the user has sufficient balance to perform an operation. However, the user's balance might be in the middle of an UPDATE statement and, in my perception, any SELECT statements performed during this period will return the old balance. My questions are:
Is my perception correct, i.e. is it possible for the SELECT statement to get old data in this trivial scenario?
If yes, how do I implement locks to protect myself from this? I've read about FOR UPDATE in the docs, but I'm not sure it is meant for this specific situation.
Please assume that I cannot serialize the requests in the clients.
for update
or to manually lock the entire table in exclusive mode before starting the update.for update
, will it block the select without changes to the update logic? That wasn't my understanding from the docsfor update
will simply lock the rows that theselect
returns. It will not change anything. It will however block any update that is issued after that (and tries to update the selected/locked rows). Another option you have is to use the serializable isolation level for both the update and the select.