Fetching a Row for Update
The FETCH statement does not ordinarily lock a row that is fetched.
Thus, another process can modify (update or delete) the fetched row
immediately after your program receives it. A fetched row is locked
in the following cases:
- When you set the isolation level to Repeatable Read, each row that you fetch is locked with a read lock until the cursor closes or until the current transaction ends. Other programs can also read the locked rows.
- When you set the isolation level to Cursor Stability, the current row is locked.
- In an ANSI-compliant database, an isolation level of Repeatable Read is the default; you can set it to something else.
- When you are fetching through an update cursor (one that is declared FOR UPDATE), each row you fetch is locked with a promotable lock. Other programs can read the locked row, but no other program can place a promotable or write lock; therefore, the row is unchanged if another user tries to modify it using the WHERE CURRENT OF clause of an UPDATE or DELETE statement.
When you modify a row, the lock is upgraded to a write lock and
remains until the cursor is closed or the transaction ends. If you
do not modify the row, the behavior of the database server depends
on the isolation level you have set. The database server releases
the lock on an unchanged row as soon as another row is fetched, unless
you are using Repeatable Read isolation. (See SET ISOLATION statement.)
Important: You can hold locks on additional
rows even when Repeatable Read isolation is not in use or is unavailable.
Update the row with unchanged data to hold it locked while your program
is reading other rows. You must evaluate the effect of this technique
on performance in the context of your application, and you must be
aware of the increased potential for deadlock.
When you use explicit transactions, be sure that a row is both fetched and modified within a single transaction; that is, both the FETCH statement and the subsequent UPDATE or DELETE statement must fall between a BEGIN WORK statement and the next COMMIT WORK statement.