sqlsql-serversql-updatewhere-clausemulti-user

Where clause of Sql - may it read a stale data?


I have a simple table (SQL Server) with one row, and many users can access this row.

If the first user does:

Update Table1 
Set Balance = Balance +10
Where FirstName= 'John' //The value in this column is "John" indeed.

Is it possible, that Balance will be updated by this first user, although an other user has entered and changed FirstName to "Dan" AFTER the row with FirstName = "John" was found by first user but BEFORE the changing of balance was done by first user?

I mean:

  1. The Where clause of the first user found the row with FirstName = "john"
  2. The second user entered, and change FirstName to "Dan".
  3. Continue from #1, the balance was updated by the first user, because the first user doesn't know that a second user has changed something (The Where clause has found the row already before the second user did something).

Solution

  • Rows are locked when they are being modified (and NOLOCK won't work in an update statement so you don't have to worry about that).

    So:

    1. First user comes along and updates the balance for John + 10.
    2. Second user updates the row and changes the name to Dan, if the first user has not committed yet, the second user will wait until the +10 balance has been committed.
    3. First user commits
    4. Second user commits
    5. Balance is +10 and the name is now Dan.
    6. If First user fires another statement for John then they won't find a row so nothing gets updated.

    If the first user fires the same update between 2 and 3 then the update will be successful as they still have the necessary row lock.