Reputation: 3143
I am using PL/SQL (Oracle 11g) to update the EMPLOYEES
table salary column.
I have used two separate scripts to do the same thing i.e update the salary of employees.
One script uses FOR UPDATE OF
statement where as another script doesn't uses it. In both cases I found that oracle holds the row level locks until we execute the ROLLBACK
or COMMIT
commands.
Then what is the difference in between two scripts?
Which one is better to use?
Here are the two scripts I am talking about:
-- Script 1: Uses FOR UPDATE OF
declare
cursor cur_emp
is
select employee_id,department_id from employees where department_id = 90 for update of salary;
begin
for rec in cur_emp
loop
update Employees
set salary = salary*10
where current of cur_emp;
end loop;
end;
--Script 2: Does the same thing like script 1 but FOR UPDATE OF is not used here
declare
cursor cur_emp
is
select employee_id,department_id from employees where department_id = 90;
begin
for rec in cur_emp
loop
update Employees
set salary = salary*10
where Employee_ID = rec.employee_id;
end loop;
end;
I found that Oracle acquired the row level locks on both cases. So, what is the benefit of using FOR UPDATE OF
and Which is the better way of coding?
Upvotes: 5
Views: 11211
Reputation: 231661
When you specify FOR UPDATE
, the row is locked at the point that you SELECT
the data. Without the FOR UPDATE
, the row is locked at the point you UPDATE
the row. In the second script, another session could potentially lock the row between the time that the SELECT
was executed and the point that you tried to UPDATE
it.
If you are dealing with a SELECT
statement that returns relatively few rows and a tight inner loop, it is unlikely that there will be an appreciable difference between the two. Adding a FOR UPDATE
on the SELECT
also gives you the opportunity to add a timeout clause if you don't want your script to block indefinitely if some other session happens to have one of the row you're trying to update locked.
Upvotes: 13