Sub topic 12
Row locks and concurrent sessions
This chapter explains what Oracle does when two sessions change the same rows at the same time. It assumes you can run INSERT, UPDATE, and DELETE, and that you know COMMIT and ROLLBACK end a transaction. It also assumes you can open two SQL*Plus, SQL Developer, or SQLcl windows. The examples use the emp_demo table from earlier chapters.
What a row lock is
When a session inserts, updates, or deletes a row, Oracle locks that row for the session's transaction. The lock lasts until the transaction ends with COMMIT or ROLLBACK. Other sessions can still read the row, but they cannot change it until the lock is released.
Oracle keeps these locks small and cheap:
- The lock is on individual rows, not on the whole table. Oracle does not escalate many row locks into a table lock.
- Readers do not block writers. A plain SELECT takes no row lock.
- Writers do not block readers. A SELECT on a locked row sees the last committed version of the row. Oracle rebuilds that version from undo data.
- Writers block other writers, but only when they target the same row.
This read behavior is called read consistency. Under the default READ COMMITTED isolation level, each statement sees the data as it was committed when the statement started. Your own uncommitted changes are visible to you and to nobody else.
Each DML statement also takes a table-level lock (a TM lock) in row-exclusive mode. Several sessions can hold this lock at once, so it does not stop concurrent DML. It does stop a conflicting DDL statement, such as DROP TABLE, from running while a transaction is open on the table.
Two sessions changing one row
Run these steps in two windows. Session A goes first.
-- Session A
UPDATE emp_demo SET salary = salary + 100 WHERE emp_id = 1;
-- 1 row updated. No COMMIT yet.-- Session B
SELECT salary FROM emp_demo WHERE emp_id = 1;
-- Returns the old, committed salary immediately. No waiting.
UPDATE emp_demo SET salary = salary + 200 WHERE emp_id = 1;
-- Hangs. Session B is waiting for Session A's row lock.Session B's UPDATE stays blocked until Session A ends its transaction. If A commits, B's UPDATE continues and applies its change to the new committed value. The final salary includes both raises. If A rolls back, B's UPDATE continues against the original value.
Rows that the two sessions do not share cause no waiting. If B had updated emp_id = 2, both statements would run at once.
Which statements take row locks
| Statement | Row locks taken |
|---|---|
| `INSERT` | The new row |
| `UPDATE` | Each row that matches the WHERE clause |
| `DELETE` | Each row that matches the WHERE clause |
| `MERGE` | Each row it updates, deletes, or inserts |
| `SELECT ... FOR UPDATE` | Each row the query returns |
| Plain `SELECT` | None |
Inserts can wait too
An INSERT locks only its own new row, but it can still wait on another session. If Session A inserts emp_id = 50 and has not committed, Session B's insert of the same key waits. Oracle cannot decide whether B's row is a duplicate until A's transaction ends.
- If A commits, B fails with ORA-00001 (unique constraint violated).
- If A rolls back, B's insert succeeds.
Foreign keys behave in a similar way. If a session inserts a child row whose parent was just inserted by another uncommitted session, the child insert waits.
Locking rows on purpose with SELECT ... FOR UPDATE
Sometimes you need to read a row and then change it, without letting anyone else change it in between. Without a lock, you can get a lost update:
- Session A reads salary 9000 and computes 9500 in the application.
- Session B reads salary 9000 and computes 9300.
- A writes 9500 and commits. B then writes 9300 and commits, and A's change is gone.
There are two fixes. The first is to let the database do the arithmetic in one statement, as in SET salary = salary + 500. The second is to lock the row when you read it:
SELECT salary
FROM emp_demo
WHERE emp_id = 1
FOR UPDATE;
UPDATE emp_demo SET salary = 9500 WHERE emp_id = 1;
COMMIT;FOR UPDATE locks every row the query returns, the same way an UPDATE would. A second session that runs the same SELECT ... FOR UPDATE waits until the first one commits or rolls back.
The lock is taken when the rows are fetched. Only the rows in the final result are locked. The final result is the rows left after all joins and filters.
Controlling how long a session waits
Waiting forever is often wrong for an interactive application. Add a wait option to the FOR UPDATE clause:
| Clause | Behavior when a row is already locked |
|---|---|
| `FOR UPDATE` | Wait with no time limit |
| `FOR UPDATE NOWAIT` | Fail at once with ORA-00054 |
| `FOR UPDATE WAIT 5` | Wait up to 5 seconds, then fail with ORA-30006 |
| `FOR UPDATE SKIP LOCKED` | Skip locked rows and return only unlocked ones |
-- Fail immediately if the row is busy
SELECT emp_id, salary
FROM emp_demo
WHERE emp_id = 1
FOR UPDATE NOWAIT;SKIP LOCKED suits work queues, where several workers each claim a different batch of rows:
SELECT emp_id, emp_name
FROM emp_demo
WHERE status = 'ACTIVE'
FOR UPDATE SKIP LOCKED;Two workers running this at the same moment get different rows, and neither waits for the other.
When the query joins several tables, FOR UPDATE locks the selected rows in every table. To lock only one table's rows, name a column from it:
SELECT e.emp_id, d.dept_name
FROM emp_demo e
JOIN dept_demo d ON d.dept_id = e.dept_id
WHERE e.emp_id = 1
FOR UPDATE OF e.salary;This locks the emp_demo row only and leaves the dept_demo row unlocked.
When locks end
A transaction releases all its row locks when it ends:
COMMITreleases them and makes the changes permanent.ROLLBACKreleases them and undoes the changes.- A session that disconnects without committing is rolled back, and its locks are released.
A partial rollback is different. ROLLBACK TO SAVEPOINT releases the locks that the transaction acquired after the savepoint. Locks taken before the savepoint stay in place, and the transaction stays open.
DDL statements such as CREATE TABLE or TRUNCATE commit the current transaction first. That commit releases your row locks as a side effect.
Deadlocks
A deadlock happens when two sessions each hold a lock the other needs:
- Session A updates
emp_id = 1. - Session B updates
emp_id = 2. - Session A updates
emp_id = 2and waits for B. - Session B updates
emp_id = 1and waits for A.
Neither session can continue. Oracle detects this after a few seconds and picks one session as the victim. The victim's current statement fails with ORA-00060 (deadlock detected while waiting for resource). The other session continues.
Only the failed statement is rolled back, not the whole transaction. The victim still holds its earlier locks, and the other session is still waiting for them. Your code must handle the error by issuing a ROLLBACK (or retrying after one), or the other session stays blocked.
Two habits prevent most deadlocks:
- Change rows in the same order in every program. If both sessions above had touched
emp_id = 1first, one would simply have waited. - Keep transactions short. Do not hold a lock while waiting for a user to type input.
Another cause is a foreign key column with no index. Deleting a parent row, or updating its key, makes Oracle check the child table. Without an index on the child's foreign key column, Oracle may lock the whole child table for the duration of the statement. This blocks unrelated inserts and updates on the child table. Index your foreign key columns, for example dept_id in emp_demo.
Finding who is blocking whom
When a statement hangs, find the blocker from a third session. You need SELECT access to the dynamic performance views, which a DBA can grant.
SELECT sid,
serial#,
username,
blocking_session,
event,
seconds_in_wait
FROM v$session
WHERE blocking_session IS NOT NULL;Each row is a waiting session. The blocking_session column holds the SID of the session holding the lock. The blocker is usually idle, waiting for a user or program that forgot to commit. Ask the owner to commit or roll back. A DBA can end the session with ALTER SYSTEM KILL SESSION 'sid,serial#', which rolls back its uncommitted work.
Common errors
| Error | Meaning | Usual action |
|---|---|---|
| ORA-00054 | Resource busy, with NOWAIT specified | Retry later, or report that the row is in use |
| ORA-30006 | Resource busy, WAIT time expired | Retry or give up |
| ORA-00060 | Deadlock detected | Roll back, then retry the transaction |
| ORA-00001 | Duplicate key found after waiting on another insert | Handle as a normal constraint error |
Exercise
Session A runs UPDATE empdemo SET salary = 8000 WHERE empid = 1 and does not commit. Session B then runs SELECT salary FROM empdemo WHERE empid = 1, and later UPDATE empdemo SET status = 'INACTIVE' WHERE empid = 1. What happens to each statement in Session B?
Show answer
The SELECT returns at once with the old committed salary, because readers are not blocked by row locks. The UPDATE waits, because Session A holds the lock on that row (the lock covers the whole row, not just the salary column). It continues when Session A commits or rolls back.
Exercise
Two worker sessions must each claim a batch of ACTIVE employees without waiting on each other. Which clause should the claiming query end with, and why does it work?
Show answer
FOR UPDATE SKIP LOCKED. Each worker locks the rows it returns, and rows already locked by the other worker are skipped, so the two workers get different rows and neither blocks.
Exercise
A deadlock occurs and your session receives ORA-00060. What happened to the transaction, and what should the code do next?
Show answer
Only the statement that caused the deadlock was rolled back. The transaction is still open and still holds its earlier locks. The code should issue a ROLLBACK (then retry the work if appropriate) so the other session can continue.