Sub topic 10
Row locks and what other sessions see
This chapter assumes you know the basics of COMMIT, ROLLBACK, and savepoints from earlier chapters. It also assumes you can open two SQL sessions at once, for example two SQL Developer worksheets or two SQLcl windows. The examples use the accounts table from the start of the tutorial.
The rule: readers and writers do not block each other
Oracle uses multiversion read consistency. A query sees the data as it was committed when the query began, so it never waits for a row that another session is changing. Reading the old version comes from undo data, which the previous chapters covered.
Two statements about concurrency follow from this:
- A
SELECTdoes not lock rows and is never blocked by row locks. - An
UPDATE,DELETE, orMERGElocks each row it changes. Another session that tries to change the same row waits.
Only writers to the same row block each other. Writers to different rows of the same table run in parallel.
What a row lock is
When a transaction changes a row, Oracle marks that row as belonging to the transaction. This is a row lock, also called a TX lock because it is tied to the transaction. The lock is held until the transaction ends with COMMIT or ROLLBACK. Rolling back to a savepoint releases the locks acquired after that savepoint, but the transaction keeps locks on rows changed before it.
Oracle stores the lock marker in the data block itself, not in a central lock table. Because of this, locking a million rows costs no more memory than locking one, and Oracle never escalates row locks to table locks.
The transaction also takes a table lock in row-exclusive mode (a TM lock). This lock only stops other sessions from running DDL on the table, such as DROP TABLE, while your transaction is open. It does not stop other DML.
Two sessions on one row
The sequence below matches the spine's example. Session A changes a row and does not commit. Session B can read the row but cannot change it.
-- Session A
UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- row 2 locked, no COMMIT yet
-- Session B
SELECT balance FROM accounts WHERE id = 2; -- returns the old, committed balance
UPDATE accounts SET balance = 0 WHERE id = 2; -- waits for Session A
-- Session A
COMMIT; -- Session B's UPDATE now proceedsSession B's UPDATE appears to hang. Nothing is wrong. It is waiting for Session A to end its transaction.
What each session sees
Session A sees its own uncommitted change immediately. Every other session sees the committed value of the row until Session A commits. After the commit, Session B's next statement sees the new value.
Consider what happens when Session B's waiting UPDATE finally runs. Under READ COMMITTED, the default isolation level, Oracle re-evaluates the WHERE clause against the newly committed row. If the row still matches, the update goes ahead on the new value. If it no longer matches, the row is skipped. This is why SET balance = balance + 10 stays correct under concurrency: it is applied to the latest committed balance, not to a stale copy.
A lost update happens when code reads a value, computes a new one in the application, and writes it back. Two sessions can both read 200 and both write their own result, and one write is silently lost. Prefer a relative update such as balance = balance + 10. If you must compute in the application, lock the row first.
Locking rows explicitly with FOR UPDATE
SELECT ... FOR UPDATE locks the selected rows without changing them. Use it when you need to read a row and then make a decision before writing.
SELECT balance
FROM accounts
WHERE id = 1
FOR UPDATE;
-- Decide in your program, then:
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;By default FOR UPDATE waits indefinitely if another session holds the lock. You can change that:
| Clause | Behavior when a row is already locked |
|---|---|
| `FOR UPDATE` | Waits until the lock is released |
| `FOR UPDATE NOWAIT` | Fails at once with ORA-00054 |
| `FOR UPDATE WAIT 5` | Waits up to 5 seconds, then fails with ORA-30006 |
| `FOR UPDATE SKIP LOCKED` | Skips locked rows and returns only the unlocked ones |
SKIP LOCKED suits work queues, where several workers each take a different batch of rows. Note that the set of rows returned depends on what other sessions are doing, so do not use it for reports that must be complete.
SELECT id, owner
FROM accounts
WHERE balance > 100
FOR UPDATE SKIP LOCKED;Seeing who is blocking whom
When a session hangs, find the blocker. In a second session, query V$SESSION. You need the SELECT privilege on the view, or a DBA to run it for you.
SELECT sid,
serial#,
username,
blocking_session,
event,
seconds_in_wait
FROM v$session
WHERE blocking_session IS NOT NULL;The blocking_session column holds the sid of the session that holds the lock. The usual cause is a session that ran DML and then went idle without committing, for example a worksheet left open. The fix is to commit or roll back in that session. Killing a session rolls back its work, so ask before you do it.
Other situations where one session waits for another
Row locks on the same row are the most common cause of waiting, but not the only one.
- Same unique key. If Session A inserts a row with primary key 5 and has not committed, Session B's insert of key 5 waits. If A commits, B gets a unique-constraint error (ORA-00001). If A rolls back, B succeeds.
- Unindexed foreign keys. Deleting a parent row, or updating its key, can take a table-level lock on the child table when the child's foreign key column has no index. Index your foreign key columns to avoid this.
- DDL. An
ALTER TABLEneeds a table lock that conflicts with the row-exclusive lock held by open DML transactions. Oracle normally fails the DDL with ORA-00054 instead of waiting.
Deadlocks
A deadlock occurs when two sessions each hold a lock the other needs.
-- Session A
UPDATE accounts SET balance = balance - 1 WHERE id = 1;
-- Session B
UPDATE accounts SET balance = balance - 1 WHERE id = 2;
-- Session A
UPDATE accounts SET balance = balance + 1 WHERE id = 2; -- waits for B
-- Session B
UPDATE accounts SET balance = balance + 1 WHERE id = 1; -- would wait for A foreverOracle detects the cycle after a few seconds and raises ORA-00060 in one of the sessions. Only the statement that detected the deadlock is rolled back, not the whole transaction. That session's earlier changes and locks remain, and the other session is still waiting. Your code should handle ORA-00060 by rolling back the transaction and retrying it.
The best prevention is a consistent order. If every transfer locks the lower id first, the cycle above cannot form.
Locks and isolation levels
The behavior above describes READ COMMITTED. The other levels differ in what happens when a conflict is found:
- SERIALIZABLE. The transaction sees a snapshot as of its start. If it tries to change a row that another transaction changed and committed after that start, Oracle raises ORA-08177 ("can't serialize access for this transaction"). Your code must be ready to retry the whole transaction.
- READ ONLY. The transaction sees a consistent snapshot, takes no row locks, and cannot run DML.
Common mistakes
- Leaving a transaction open while waiting for user input. The locks stay held and other sessions queue behind it.
- Treating
SELECT ... FOR UPDATEas free. It holds locks until the transaction ends, so keep the gap between locking and committing short. - Locking rows in different orders in different code paths, which invites deadlocks.
- Handling ORA-00054 or ORA-00060 by ignoring it. Both mean the work did not happen.
Exercise
Session A runs UPDATE accounts SET balance = balance - 100 WHERE id = 1; and does not commit. Session B then runs SELECT balance FROM accounts WHERE id = 1;, then UPDATE accounts SET owner = 'Alicia' WHERE id = 1;, and finally UPDATE accounts SET balance = balance + 5 WHERE id = 2;. Which of Session B's statements wait, and what does the SELECT return?
Show answer
The SELECT does not wait and returns the old committed balance (1000), because readers are not blocked by row locks and see data as of the last commit. The UPDATE of row 1 waits, even though it changes a different column, because the lock is on the whole row. The UPDATE of row 2 does not wait, because Session A has not locked that row.
Exercise
Two sessions each run SELECT * FROM accounts WHERE id = 1 FOR UPDATE NOWAIT; at nearly the same time. What does the second session get, and why is this different from a plain FOR UPDATE?
Show answer
The second session receives ORA-00054 ("resource busy and acquire with NOWAIT specified") immediately, because the first session already holds the row lock. A plain FOR UPDATE would instead wait until the first session commits or rolls back.