When does select for update release locks

Hello all,
Does anyone know when Oracle realeases the row locks when a
select for update is issued?
Does Oracle realase the row lock at the time when an actual update statement is
issued for the locked row, or does it wait until a commit statment is executed?
So for example, can I lock several rows with a select for update clause, and then
issue update statements as many times as I want on each locked row without
having to worry about the lock being released until I issue a commit statement.
Thanks,
David

yes.
The lock is released only when your transaction ends. A transaction can end because of:
1). Commit.
2). Rollback.
3). client disconnects.
etc. etc...

Similar Messages

  • When is SELECT FOR UPDATE used

    DB version:10gR2
    Since another thread of mine on this subject didn't go well, i am starting another thread.
    When exactly is SELECT..FOR UPDATE statement used? With the exception of using SELECT...FOR UPDATE in CURSOR declaration, I've rarely seen SELECT ...FOR UPDATE being used explicitlyby PL/SQL gurus in our firm. Why didn't they use SELECT..FOR UPDATE(i mean a stand alone SELECT FOR UPDATE, <em>not as a part of Cursor</em>) to lock rows before UPDATE/DELETE/INSERT in their codes?
    Edited by: M.Everett on Oct 20, 2008 12:00 PM
    edited the initial post to let the users know that I am refering to a stand alone SELECT FOR UPDATE statement, not the part of a cursor

    M.Everett wrote:
    What i gather from various sources in the Internet:
    1. SELECT FOR UPDATE is used mainly on CURSORs and very rarely used as a stand alone statement (if this is not the case you would have seen SELECT FOR UPDATE statements before every UPDATEs and DELETEs in PL/SQL codes)
    2. Stand alone SELECT FOR UPDATEs are used mainly when dealing with CLOB, BLOB
    Am i right in making these conclusions?1. This is probably a fair assumption.
    2. Not really. SELECT FOR UPDATE is not a requirement when dealign with (C|B)LOBs.
    SELECT FOR UPDATE allows an easy form of reference when you come to update rows in a cursor loop (although cursor loops should be rarely used), because rather than having to include a where condition on key columns you can just refer to the CURRENT ROW. Obviously, the main reason for using SFUs is the locking and this can become a requirement in some business environments where a user "picks up" a record to deal with and other users will then not see that record in their list or be able to select it for themselves.
    ;)

  • Select for update that doesn't return any rows

    Are there any odd side-effects that may occur if a select for update that returns no results is never committed? I wouldn't think there are, but I'm not sure if there would be some kind of overhead or unforeseen consequences. This isn't a terribly important question, but it's come up in some coding I've done and I've not been able to find any documentation addressing it.

    A select for update only locks rows that meet the predicate specified in the where clause. So, if the query returns no rows, no rows are locked.
    session1> SELECT * FROM t;
            ID DESCR
             1 Un
             5 One
             2 THIS IS WA
    session1> SELECT * FROM t
      2  WHERE id = 11 FOR UPDATE;
    no rows selectedA second session can update rows in the table
    session2> UPDATE t
      2  SET descr = 'One'
      3  WHERE id = 1;
    1 row updated.John
    Edited by: John Spencer on Jan 7, 2009 1:36 PM
    I just realized that, although you can do updates on the table after the select fo update that returns no rows, you cannot do DDL operations liike a truncate. Unless the session that does the select for update either ends the transaction (i.e. commit or rollback) or ends the session DDL operations will fail.

  • Strange behavior of select for update

    I observed a strange behavior of "select .. for update" statement in binary xml table. Here is the piece of code:
    create table xmltab of XMLType XMLTYPE store as binary xml;
    Table created.
    insert into xmltab values('<x><y>y1</y><z>z1</z></x>');
    1 row created.
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' and
    extractValue(x.object_value,'/x/z')='z1' ;
    OBJECT_VALUE
    <x>
      <y>y1</y>
      <z>z1</z>
    </x>
    The following query doesn't return any row!!
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' and
    extractValue(x.object_value,'/x/z')='z1' for update;
    no rows selected
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='b1' for update;
    OBJECT_VALUE
    <x>
      <y>b1</y>
      <z>z1</z>
    </x>
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/z')='z1' for update;
    OBJECT_VALUE
    <x>
      <y>b1</y>
      <z>z1</z>
    </x>
    The following one returns correct result !!
    select x.object_value, extractValue(x.object_value,'/x/y'), extractValue(x.object_value,'/x/z')
    from xmltab x
    where extractValue(x.object_value,'/x/y')='b1' and
    extractValue(x.object_value,'/x/z')='z1' ;
    OBJECT_VALUE
    EXTRACTVALUE(X.OBJECT_VALUE,'/x/y')
    EXTRACTVALUE(X.OBJECT_VALUE,'/x/z')
    <x>
      <y>b1</y>
      <z>z1</z>
    </x>
    b1
    c1
    I get expected result for all the cases if the table is created in the following way
    create table xmltab of XMLType;
    Can anyone tell me why does select for update behaves in this strange way for binary xml table?

    Sorry for copy paste problem. b1 should be replaced with y1 and c1 with z1.
    Here is the correct code.
    create table xmltab of XMLType XMLTYPE store as binary xml;
    Table created.
    insert into xmltab values('<x><y>y1</y><z>z1</z></x>');
    1 row created.
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' and
    extractValue(x.object_value,'/x/z')='z1' ;
    OBJECT_VALUE
    <x>
      <y>y1</y>
      <z>z1</z>
    </x>
    The following query doesn't return any row!!
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' and
    extractValue(x.object_value,'/x/z')='z1' for update;
    no rows selected
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' for update;
    OBJECT_VALUE
    <x>
      <y>y1</y>
      <z>z1</z>
    </x>
    select x.object_value
    from xmltab x
    where extractValue(x.object_value,'/x/z')='z1' for update;
    OBJECT_VALUE
    <x>
      <y>y1</y>
      <z>z1</z>
    </x>
    The following one returns correct result !!
    select x.object_value, extractValue(x.object_value,'/x/y'), extractValue(x.object_value,'/x/z')
    from xmltab x
    where extractValue(x.object_value,'/x/y')='y1' and
    extractValue(x.object_value,'/x/z')='z1' ;
    OBJECT_VALUE
    EXTRACTVALUE(X.OBJECT_VALUE,'/x/y')
    EXTRACTVALUE(X.OBJECT_VALUE,'/x/z')
    <x>
      <y>y1</y>
      <z>z1</z>
    </x>
    y1
    z1
    I get expected result for all the cases if the table is created in the following way
    create table xmltab of XMLType;
    Can anyone tell me why does select for update behaves in this strange way for binary xml table?

  • Is SELECT FOR UPDATE lock ever released?

    Hi,
    Does any one know whether the lock acquired by SELECT FOR UPDATE will ever be released if user session ends without commit or rollback(e.g. crashed)? If it does, is there a default parameter to control the maximum wait time for Oracle to release the lock automatically?
    Thanks,
    JM

    Your select statement won't be committed if the db crashes. That is a DML (data manipulation language)statement. In your scenario everything is rolled back upto the last commit or savepoint. For DDL (data definition Language) for the same situation you would get an implicit commit.
    Hope this helps.

  • Oracle select for update: not releasing lock

    My JDBC code uses "select for update" to modify record in Oracle database. I tried to simulate network connection down situation.
    After my JDBC code locked on a record using "select for update", I unplugged the network cable. I then tried to run the same code on another computer, but it could not accquire the lock, because the previous lock was not released. I tried sqlplus to lock the record, but failed also. The lock has been there for at least an hour now. I guess it may finally be released, but is there a way for oracle to release the lock as soon as the connection is down? Not know if it is a JDBC setting or oracle setting.

    Dear Friend,
    What you are trying to do is not correct way of checking the concurrency and transaction.
    The reason is as listed below.
    01.Always remember http is a stateless protocol and removing the connection or just closing the browser will never be informed to the database or to the application server thus the transaction monitor (TM)or processor will never release the lock as it will deem that the actor is manipulating the data.
    02.As per locking goes every database is having a �TM� and the default isolation level setting is different like oracle uses serializable DB2udb 7.0 or db2/As400 uses repeatable read. You can change this setting by editing the default setting in the database but be very sure before touching it.
    03.     You can also transpose this with your Application server setting for that piece of code or Globally but again be very sure about it as it will change the entire gamete.
    04.     For releasing lock you have to manually do it or you can change the settings of App server or the Database to release the connection after some wait time.
    Regards,
    Ruchir

  • Inconsistent Locking with Select for Update

    Hi,
    I seem to be having some issues in using SELECT FOR UPDATE and was hoping to get some insight from the Oralce Guru's out there.
    I have a J2EE application, running in WebLogic 8.1.4 using Oralce 9.2.0.1.0.
    The application contains code that requires locking to be done on a specific table with multiple transactions (tx) requesting the same lock. Eg:
    Tx 1: Select * from Zone where Zoneid = 'Zone1' for update (Obtains lock)
    Tx 2: Select * from Zone where Zoneid = 'Zone1' for update (waits)
    Tx 100: Select * from Zone where Zoneid = 'Zone1' for update
    Tx1 commits.
    It appears that the following transactions, i.e. Tx2 - Tx100 do not seem to execute in the order the lock was requested. That is Tx 100 always appears to be the second last transaction to execute, after which some arbitrary transaction between Tx2 - Tx99 will execute after Tx100 has committed.
    This seems to tell me that the lock is not being handed in a FIFO manner and is causing us great pain as our data is not longer consistent.
    Does anyone know how i might be able to trace which transaction is being awarded the lock? Also if anyone has any suggestion on how to troubleshoot/solve this issue, greatly appreciated.
    TIA
    Prem

    Oracle does not have a lock queue/manager at all. The locked status of a record is essentially an attribute of the record itself. It is stored on the datablock header. When a transaction requests a lock and can't get it, and is willing to wait (SELECT FOR UPDATE without NOWAIT), it first spins while waiting for the lock (four times as I recall), then sleeps waiting for the lock. The the more times it sleeps before getting the lock, the longer it will sleep before trying again.
    What is likely happening here is that transaction 100 is still spinning when transaction 1 commits, so checks back more frequently and gets the lock first. The rest get the lock whenever they wake up and noone else has taken the lock.
    If you need the transaction to occur in order, then I do not think you can use Oracle's native locking mechanism. Depending on what exactly you are trying to do, you may want to look at Advanced Queueing, or possibly the built-in package DBMS_LOCK.
    HTH
    John

  • Database select for update locks ADF

    Hi,
    When a user has initiated an update session in an adf application and locking is optimistic it will acquire a lock on table row using select for update no wait; . But when the user closes a tab the session would not be terminated. Now i know as HTTP is a stateless protocol, we can wait for the timeout and then the lock will be released using a session listener implementation. But if the user instead tries to log in again in a new tab and tries to edit the same record he will receive a message stating that another user already holds a lock on the record which is correct, but is misleading.
    So can we rely on javascript for these scenarios that as soon as the user closes the tab the session should be terminated.
    Here's a snippet
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js" ></script>
    <script type="text/javascript">
    var unLoad = function() {
        dojo.io.script.get({
        url:'http://127.0.0.1:7101/myapp/adfAuthentication?logout=true',
        timeout:15000,
      dojo.addOnWindowUnload(unLoad);
    </script>I know this might not work always as it depends on the fact that request might / might not be processed by the server.
    Are there any alternate solutions and also reducing the session timeout is ruled out in my scenario.

    Ramandeep,
    So are there other alternatives or solutionsAlternatives or solutions to what, exactly? As Jobinesh has told you, as long as you use optimistic locking, ADF doesn't acquire database locks except in the context of a transaction that is going to be completed in the current HTTP request. You could obviously force ADF to deviate from this if you called "postChanges" during an HTTP request and leave the transaction hanging, but that would just be wrong in an optimistic locking scenario - the solution would be "don't do that."
    John

  • Lock Cascade With Select for UPDATE

    If I had a employee table and a phone table with a parent/child relationship and a primary key constraint on the employee table-will issuing a select for update on the employee also lock the corresponding child rows on the phone table ?
    If not how can I bring this about ?

    You only need two sessions:
    First session: Issue the 'select for update'
    statements for the row(s) in both tables, don't
    rollback or commit
    Second session: try to update a row that you tried to
    lock in the first session (with NOWAIT).
    Thanks. I can try this definitely. A basic question.
    You are asking me to do a join on both the tables right ?
    Not two individual SQL statements ?
    Updating the primary key is known as a Bad Idea (tm).
    The key should never be touched because it should be
    meaningless. When you have a column that holds 'real'
    information it is no candidate for a primary key.
    Rgds,
    GuidoYes I am aware of that. I was just wondering what is the meaning behind this statement from this link ?
    http://www.akadia.com/services/ora_locks_survival_guide.html
    And the exact phrase from that link under the section Referential Integrity Locks (RI Locks)
    "RI constraints are validated by the database via a simple SELECT from the dependent (parent) table in question-very simple, very straightforward. If a row is deleted or a primary key is modified within the parent table, all associated child tables need to be scanned to make sure no orphaned records will result. "
    Thanks again.

  • Select for update returns no rows even though there is no locking thread

    I'm using Ibatis library over oracle sql for my query. The select for update statement returns no rows. This happens intermittently. When this was happening last time, I executed the select statement on sqldeveloper (but without the 'for update') and got rows. This situation is not easily reproducible so I've not yet been able to ascertain whether rows are returned on sqldeveloper with the 'for update' clause. But I know for sure that there was no other thread locking the rows. How could this be happening?

    The select for update statement returns no rowsWhy do you think that a select for update will always return rows?
    the for update clause if there not to garantee the presence of rows but to lock the row when it is present
    sql> select * from t;
             A          B C
             1          1 step1
             2          2 step2
             3          3 step3Then session 1 issues the following select
    SELECT     *
          FROM t
         WHERE a = 1
    FOR UPDATE NOWAIT;If session 2 issues the same select before session 1 commits or rolls back
    SELECT     *
          FROM t
         WHERE a = 1
    FOR UPDATE NOWAIT;It will get the following error
    ERROR at line 1:
    ORA-00054: resource busy and acquire with NOWAIT specifiedBut if session 2 issue such a kind of select
    sql> SELECT     *
      2        FROM t
      3       WHERE a = 99
      4  FOR UPDATE NOWAIT;
    no rows selectedYou see then that a select for update can return no rows
    Best Regards
    Mohamed Houri

  • SELECT FOR UPDATE with the SKIP LOCK clause

    Hi,
    I have a query regarding the SELECT FOR UPDATE with the SKIP LOCK clause.
    Whether this will be really good for parallel processing.
    Also if we are selecting a set of records in a cursor whether the lock will be done at the records level once we fetch the records?
    Also do we have any known issues with this one?
    We are trying to figure out whether this will fit for business requirement, we are trying to do a implement a threading kind of thing for our stored procedure invocation in background using shell script.
    Any suggestion or feedback on this will be helpful for us.
    Thanks a lot for the support given....
    Regards,
    Basil Abraham.

    http://www.oracle.com/technology/oramag/oracle/08-mar/o28plsql.html
    Please read the above thread for few information...Thanks!

  • DBMS_LOCK vs Select for update locking

    Hi,
    In one of our database packages, we are using the dbms_lock (that package is used to generate unique numbers) instead of select for update locking.
    I want to ask what is more suitable here. Our application is oracle forms and oracle db on oracle app server.
    Are there any limitations to select for update locking?
    What are the conditions favourable to use DBMS_LOCK?
    Regards,

    DBMS_LOCK is extremely efficient. Try it. Put a call to obtain/free a lock in a loop and see how long it takes to loop a few thousand times (don't SLEEP in the loop, just obtain and free the lock). If you are having performance issues with DBMS_LOCK or your select it is probably because whatever it is that gets the lock (whichever way you get it) is taking a certain amount of time to finish.
    I too, am curious as to what "issues" you had. In either case, a lock for consistent read will be different than a lock for update (as it should be) in terms of how it impacts other users.

  • LOCK TABLE vs select for update

    Hello All,
    if the requirement is to lock an entire huge table to prevent any users from performing any update statement, which statement has more performance gain and why: LOCK TABLE or select fro update nowait?
    is there any overhead of using LOCK TABLE statement?
    Thanks,

    The reason I said to revoke update privilege is because I do not understand the requirement. Why do you want to prevent users from updating the table? I am assuming that users should never be allowed to update the table. In that case locking the table and select for update would be no good. If you want to stop users from updating while some one else is updating, why? All the lock table or select for update will do is cause their session to wait (hang) until the locking process commits or rolls back. This could generate a few (sic) complaints that the user application is slow/freezing.
    If you can state the business problem, perhaps we can offer a solution.

  • SELECT FOR UPDATE - does it write to REDO?

    Greetings folks,
    we have some strange performance issues with a recent application update. This is custom in-house application. Every morning since the deploy we get a spike in load, especially to log sync / redo archive. We capture activity surrounding the load, and found many "select for update" statements.
    Im digging through metalink and docs looking to confirm "write or no write" to the redo log files. comments appreciated.

    sb92075 wrote:
    SELECT does not generate REDO
    DML generates REDO.It is possible for a SELECT to generate redo due to the effects of delayed block cleanout. A small test case:
    Session 1:
    CREATE TABLE T10 AS
    SELECT
      ROWNUM RN
    FROM
      DUAL
    CONNECT BY
      LEVEL<=1000;
    UPDATE
      T10
    SET
      RN=RN;
    UPDATE
      T10
    SET
      RN=RN;
    UPDATE
      T10
    SET
      RN=RN;
    Session 2:
    ALTER SYSTEM FLUSH BUFFER_CACHE;
    ALTER SYSTEM FLUSH BUFFER_CACHE;
    Session 1:
    COMMIT;
    Session 2:
    SET AUTOTRACE ON STATISTICS
    SELECT
    FROM
      T10;
    1000 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             73  consistent gets
              3  physical reads
            188  redo size
          11104  bytes sent via SQL*Net to client
           1060  bytes received via SQL*Net from client
             68  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
           1000  rows processedNote that the above may be performed in a single session rather than using two sessions. Essentially, the flush of the buffer cache causes the dirty blocks (containing uncommitted changes) to be written to disk, and the blocks are "cleaned up" during the next SELECT which accesses the blocks.
    A much better explanation:
    http://jonathanlewis.wordpress.com/2009/06/16/clean-it-up/
    Charles Hooper
    IT Manager/Oracle DBA
    K&M Machine-Fabricating, Inc.

  • Deadlock detected during SELECT FOR UPDATE - an application error?

    I have a general question about how Oracle prevents deadlocks from affecting
    applications: do I need to build support into the application for handling
    deadlocks when they occur in this particular scenario, or should Oracle handle
    this for me? I'd like to know whether this is "normal" behavior for an Oracle
    application, or if there is an underlying problem. Consider the following situation:
    Two sessions issue individual SELECT FOR UPDATE queries. Each query locates
    records in the table using a different index. These indexes point to rows in a
    different order from each other, meaning that a deadlock will occur if the two
    statement execute simultaneously.
    For illustrative purposes, consider these rows in a hypothetical table.
    ALPHABET
    alpha
    bravo
    charlie
    delta
    echo
    foxtrot
    golf
    hotel
    Index A results in traversing the table in ascending alphabetical order; index
    B, descending. If two SELECT FOR UPDATE statements concurrently execute on this
    table--one with an ascending order execution path and one in descending order--
    the two processes will deadlock at the point where they meet. If Session A
    locks alpha, bravo, charlie, and delta, while Session B locks hotel, golf,
    foxtrot, and echo, then neither process can proceed. A needs to lock echo, and
    B needs to lock delta, but one cannot continue until the other releases its
    locks.
    This execution path can be encouraged using hints. Executing queries similar to these on larger tables will generate the "collision" as described above.
    -- Session A
    select /*+ index_asc (customer) */
    from customer
    where gender = 'M'
    for update;
    -- Session B
    select /*+ index_desc (customer) */
    from customer
    where gender = 'M'
    for update;
    Oracle will recognize that both sessions are in a stand-off, and it will roll
    back the work performed by one of the two sessions to break the deadlock.
    My question pivots on whether or not, in this situation, the deadlock gets
    reported back to the application executing the queries as an ORA-00060. If
    these are the ONLY queries executed during these sessions, I would think that
    Oracle would rollback the locking performed in one of the SELECT FOR UPDATE
    statements. If I understand correctly,
    (1) Oracle silently rolls back and replays work performed by UPDATE statements
    when a deadlock situation occurs within the scope of the update statement,
    and
    (2) A SELECT FOR UPDATE statement causes Oracle, at the point in time the cursor
    is opened, to lock all rows matching the WHERE clause.
    If this is the case, then should I expect Oracle to produce an ORA-00060
    deadlock detection error for two SELECT FOR UPDATE statements?
    I would think that, for deadlock situations completely within Oracle's control,
    this should be perceived to the application invoking the SELECT FOR UPDATE
    statements as regular blocking. Since the query execution plans are the sole
    reason for this deadlock situation, I think that Oracle would handle the
    situation gracefully (like it does for UPDATE, as referenced in (1)).
    Notice, from the trace file below, that the waits appear to be from row locking,
    and not from an artificial deadlock (e.g. ITL contention).
    Oracle8i Enterprise Edition Release 8.1.7.4.0 - 64bit Production
    With the Partitioning option
    DEADLOCK DETECTED
    Current SQL statement for this session:
    SELECT XXX FROM YYY WHERE ZZZ LIKE 'AAA%' FOR UPDATE
    ----- PL/SQL Call Stack -----
    object line object
    handle number name
    58a1f8f18 4 anonymous block
    58a1f8f18 11 anonymous block
    The following deadlock is not an ORACLE error. It is a
    deadlock due to user error in the design of an application
    or from issuing incorrect ad-hoc SQL. The following
    information may aid in determining the deadlock:
    Deadlock graph:
    ---------Blocker(s)-------- ---------Waiter(s)---------
    Resource Name process session holds waits process session holds waits
    TX-002f004b-000412cf 37 26 X 26 44 X
    TX-002e0044-000638b7 26 44 X 37 26 X
    session 26: DID 0001-0025-00000002     session 44: DID 0001-001A-00000002
    session 44: DID 0001-001A-00000002     session 26: DID 0001-0025-00000002
    Rows waited on:
    Session 44: obj - rowid = 0000CE31 - AAANCFAApAAAAGBAAX
    Session 26: obj - rowid = 0000CE33 - AAANCHAArAAAAOmAAM
    Thanks for your insight,
    - Curtis
    (1) "Oracle will silently roll back your update and restart it"
    http://tkyte.blogspot.com/2005/08/something-different-part-i-of-iii.html
    (2) "All rows are locked when you open the cursor, not as they are fetched."
    http://download-east.oracle.com/docs/cd/A87860_01/doc/appdev.817/a77069/05_ora.htm#2170
    Message was edited by:
    Curtis Light

    Thanks for your response. In my example, I used the indexes to force a pair of query execution plans to "collide" somewhere in the table in question by having one query traverse the table via index in an ascending order, and another in descending. This is an artificial scenario for reproducible illustrative purposes, but similar collisions could legitimately occur in real world scenarios (e.g. a full table scan and an index range scan with lookup by ROWID).
    So, with that said, I think it would be unreasonable for Oracle to report the collision as a ORA-00060 every time it occurs because:
    (1) The UPDATE statement handles this situation automatically, and
    (2) An ORA-00060 results in a 100+KB trace file being written out, only rational for truly erroneous situations.
    I agree that, when the application misbehaves and locks rows out of order in separate SQL statements, then Oracle should raise an ORA-00060, as the deadlock is outside of its control. But in this case, the problem occurs with just two individual SQL statements, each within its own transaction.

Maybe you are looking for