Updatable Cursors (FOR UPDATE) βοΈ¶
Mentor's Note: Usually, a cursor is "Read-Only". But sometimes you want to "Lock" a row while you are looking at it and change its data immediately. This is what we call an Updatable Cursor. π‘
π The Scenario: The Bank Audit π°¶
Imagine you are a bank auditor. - You are going through a list of accounts. - When you find an account with a negative balance, you want to Apply a Fine immediately. - You don't want to search for the ID againβyou just want to change the record you are currently holding in your hand. β
π» 1. The FOR UPDATE Clause¶
First, you must tell Oracle you intend to change the data by adding FOR UPDATE to your query. This Locks the rows so nobody else can change them while you are working.
DECLARE
CURSOR c_sal IS
SELECT salary FROM employees
WHERE department_id = 10
FOR UPDATE; -- π Lock these rows
π» 2. The WHERE CURRENT OF Clause π¶
This magic clause tells Oracle: "Update the exact row that this cursor is currently pointing to."
BEGIN
FOR r IN c_sal LOOP
-- π Action: Give everyone in Dept 10 a small raise
UPDATE employees
SET salary = salary + 100
WHERE CURRENT OF c_sal; -- π― Target current row
END LOOP;
COMMIT; -- π Release locks
END;
π‘οΈ 3. Why use this? (Architect's Note)¶
- Accuracy: You avoid "Race Conditions." If you used
WHERE id = r.id, another user could potentially delete that ID between your SELECT and your UPDATE.WHERE CURRENT OFis much safer. - Performance: It is faster because Oracle already has the physical address (ROWID) of the row. It doesn't have to search the index again. β‘
- Pessimistic Locking:
FOR UPDATEis great for high-stakes banking or inventory systems where you must ensure data doesn't change while you calculate.