Skip to Main Content
  • Questions
  • Explicit Row Locking from PL/SQL function

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question, Tejas.

Asked: January 06, 2002 - 1:09 pm UTC

Last updated: February 12, 2007 - 10:17 am UTC

Version: 8

Viewed 1000+ times

You Asked

Dear Sir,

How to explicitly Lock/unlock the row(s) of a table ?
I want to hold the lock until I explicitly release
(the lock should not be released on commit/rollback)

Please explain with some example.

Thanks

Tejas


and Tom said...

commit and rollback always unlocks a row. No avoiding it.

To explicitly LOCK -- select .... where ... FOR UPDATE;

that'll lock it from other updates.

Commit/rollback = locks on rows are gone.


If you want to implement your OWN locking scheme, you can use dbms_lock (see the supplied packages guide). This lets you create locks that can be gotten and released on demand and persist across commits.

Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Tejas, January 08, 2002 - 1:08 pm UTC

I think, dbms_lock is not actually locking any row(s).

If one user holds the lock in exclusive mode then other user
can not hold the "same" lock. But it does not prevent the direct update of the row (by using update table set ...).

Please let me know, What I understood is true or not ?

Could I prevent these row(s) from updating by other users, while associated lock (using dbms_lock) is held by an user ?



Tom Kyte
January 08, 2002 - 2:15 pm UTC

You can, if you write you OWN data access layer (eg: an API).

Instead of allowing:


update t set x = ... where pk = ....

you write a procedure

procedure p( p_pk in number, p_x in varchar2 )
is
begin
dbms_lock -- get a lock named after the primary key
update the row
end;


don't let people do updates, let them use an API.



Unlock Only a Subset of Locked Rows

Ed, February 10, 2007 - 2:14 pm UTC

Bringing this back after 5 years...

Tom, you said
>> Commit/rollback = locks on rows are gone.
SQL> select * from emp where empno in (7369, 7521, 7698) for update ;

EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 7369 SMITH      CLERK      7902 17-Dec-1980    800.00               20
 7521 WARD       SALESMAN   7698 22-Feb-1981   1250.00    500.00     30
 7698 BLAKE      MANAGER    7839 01-May-1981   2850.00               30


Is there a way to release lock on empno = 7521 only ?
still locking the other 2

thanks

10gR2
Tom Kyte
February 12, 2007 - 10:17 am UTC

nope.

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library