Sub topic 10
Locking and updating rows with FOR UPDATE and WHERE CURRENT OF
This chapter assumes you can write an explicit cursor, use a cursor FOR loop, and handle exceptions in a PL/SQL block. It covers how to lock the rows a cursor selects and how to update the row the cursor is currently positioned on.
Why lock rows at all
A plain SELECT in Oracle never blocks other sessions, and other sessions never block it. This causes a problem when you read a row, decide something from its value, and then update it. Between your read and your update, another session can change the same row. Your update then overwrites that change, which is called a lost update.
SELECT ... FOR UPDATE closes that gap. It locks the selected rows when the cursor is opened. Other sessions can still read them, but they cannot update, delete or lock them until your transaction ends.
The basic pattern
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE OF salary NOWAIT;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE CURRENT OF c_emp;
END LOOP;
COMMIT;
END;
/The example has three parts:
FOR UPDATEin the cursor query locks the rows.WHERE CURRENT OF c_empmakes theUPDATE(orDELETE) apply to the row the cursor last fetched.COMMITafter the loop ends the transaction and releases the locks.
WHERE CURRENT OF is only legal for a cursor declared with FOR UPDATE. Without that clause the compiler raises an error.
When the locks are taken
Locks are acquired when the cursor is opened, not row by row as you fetch. In a cursor FOR loop, the implicit OPEN happens when the loop starts. At that moment Oracle locks every row the query returns, and the result set is fixed as of that moment.
This has two consequences:
- Errors from lock conflicts surface at
OPEN, before any row is processed. Put the exception handler around the whole loop. - Locking a large result set holds many locks for as long as your transaction runs. Keep the
WHEREclause selective.
Options on the FOR UPDATE clause
By default, if another session holds a lock on a selected row, your OPEN waits indefinitely. These options change that behavior.
| Clause | Behavior when a row is already locked |
|---|---|
| `FOR UPDATE` | Waits until the other transaction ends |
| `FOR UPDATE NOWAIT` | Raises ORA-00054 immediately |
| `FOR UPDATE WAIT 5` | Waits up to 5 seconds, then raises ORA-30006 |
| `FOR UPDATE SKIP LOCKED` | Skips the locked rows and returns only the rows it could lock |
You can combine OF column with any of them, for example FOR UPDATE OF salary SKIP LOCKED.
Handling a busy row
Oracle raises ORA-00054 as an unnamed error. Give it a name with PRAGMA EXCEPTION_INIT so you can handle it clearly.
DECLARE
e_busy EXCEPTION;
PRAGMA EXCEPTION_INIT(e_busy, -54);
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE OF salary NOWAIT;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE CURRENT OF c_emp;
END LOOP;
COMMIT;
EXCEPTION
WHEN e_busy THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Rows are locked by another session. Try again later.');
END;
/For WAIT n, the timeout error is ORA-30006. Map it the same way with PRAGMA EXCEPTION_INIT(e_timeout, -30006).
Choose between the two like this:
- Use
NOWAITin interactive code, where you would rather tell the user than make them wait. - Use
WAIT nin batch code that can tolerate a short delay. - Use plain
FOR UPDATEonly when waiting indefinitely is acceptable, because a forgotten open transaction in another session can hang your program.
What OF column really does
In a single-table query, OF salary changes nothing about which rows are locked. It is mostly documentation. The clause matters in a join:
DECLARE
CURSOR c_emp IS
SELECT e.employee_id, e.salary, d.department_name
FROM employees e
JOIN departments d ON d.department_id = e.department_id
WHERE d.department_id = 50
FOR UPDATE OF e.salary;
BEGIN
FOR r IN c_emp LOOP
UPDATE employees
SET salary = r.salary + 100
WHERE CURRENT OF c_emp;
END LOOP;
COMMIT;
END;
/Without OF, Oracle locks the selected rows in every table in the join. With OF e.salary, it locks only rows in employees, the table that owns that column. Locking fewer tables reduces contention, so name the columns of the table you plan to change.
Skipping locked rows for work queues
SKIP LOCKED lets several sessions share a pool of rows without blocking each other. Each session claims the rows nobody else holds.
DECLARE
CURSOR c_pending IS
SELECT employee_id
FROM employees
WHERE department_id = 50
FOR UPDATE SKIP LOCKED;
l_count PLS_INTEGER := 0;
BEGIN
FOR r IN c_pending LOOP
l_count := l_count + 1;
-- process the row here
END LOOP;
DBMS_OUTPUT.PUT_LINE('Claimed ' || l_count || ' rows');
COMMIT;
END;
/The result set depends on which locks exist at the moment of OPEN, so two runs of the same query can return different rows. Do not use SKIP LOCKED when you need every row processed in one pass.
The COMMIT inside the loop trap
A COMMIT or ROLLBACK ends the transaction and releases the locks. Oracle also invalidates the cursor's read position. If you commit inside a loop that fetches from a FOR UPDATE cursor, the next fetch typically fails with ORA-01002 (fetch out of sequence).
-- Fails on the second iteration with ORA-01002
BEGIN
FOR r IN (SELECT employee_id, salary
FROM employees
WHERE department_id = 50
FOR UPDATE) LOOP
UPDATE employees
SET salary = r.salary * 1.05
WHERE employee_id = r.employee_id;
COMMIT;
END LOOP;
END;
/You have these options:
- Commit once after the loop. This is the best choice when the data volume is modest and you want the whole change to succeed or fail together.
- Drop
FOR UPDATEand update by key (WHERE employee_id = r.employee_id). You lose the lock andWHERE CURRENT OF, so you must accept the lost-update risk or re-check the row yourself. - Process in batches, using a fresh cursor per batch and committing between batches.
Restrictions
FOR UPDATE is not allowed in a query that uses DISTINCT, GROUP BY, aggregate functions or set operators such as UNION. Oracle raises ORA-01786 at compile or open time. If you need to lock rows picked by an aggregate, select the primary keys in a subquery and lock the base rows in the outer query:
SELECT employee_id, salary
FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 10)
FOR UPDATE;Also remember these points:
ORDER BYis allowed together withFOR UPDATE.WHERE CURRENT OFworks forUPDATEandDELETEonly.- If the cursor has not fetched a row yet, or the last fetch returned no row,
WHERE CURRENT OFraises an error. In a cursor FOR loop this cannot happen inside the loop body. - The locks last for the whole transaction, not the loop. If you do other work after the loop and before
COMMIT, the rows stay locked.
Choosing between WHERE CURRENT OF and a key
WHERE CURRENT OF is fast because Oracle uses the row address from the fetch and does not search for the row again. It also guarantees you change exactly the row you read. Its costs are the locks held until the transaction ends and the ban on committing mid-loop.
Where you can express the change as one UPDATE statement, do that instead. A single set-based statement is shorter and usually much faster than any cursor loop. Use FOR UPDATE when row-by-row logic is truly required, such as calling a procedure per row or applying rules too complex for SQL.
Exercise
A cursor is declared with FOR UPDATE and a cursor FOR loop updates each row using WHERE CURRENT OF. A developer adds a COMMIT as the last statement inside the loop body, and the program now fails on the second iteration with ORA-01002. Explain why, and give one fix.
Show answer
The COMMIT ends the transaction and releases the row locks, which invalidates the FOR UPDATE cursor's position, so the next fetch is out of sequence. One fix is to move the COMMIT after END LOOP so the whole change commits once. Another is to remove FOR UPDATE and WHERE CURRENT OF, update by primary key, and accept that the rows are no longer locked.
Exercise
Two sessions run the same block with a cursor declared as FOR UPDATE SKIP LOCKED over the same 100 rows, and session A has already opened its cursor. What does session B get, and what would it get with NOWAIT instead?
Show answer
With SKIP LOCKED, session B opens without waiting and its cursor returns only the rows that session A has not locked, which here is none of the 100 if A locked them all. With NOWAIT, session B's OPEN fails immediately with ORA-00054 (resource busy) because the rows are already locked.