When should SELECT ..FOR UPDATE be used?

DB Version:10gR2
This is what 10gR2 PL/SQL documentation says about SELECT...FOR UPDATE
With the SELECT FOR UPDATE statement, you can explicitly lock specific rows of a
table to make sure they do not change after you have read them. That way, you
can check which or how many rows will be affected by an UPDATE or DELETE
statement before issuing the statement, and no other application can change the
rows in the meantime
But i don't see SELECT...FOR UPDATE much in our production codes. Is SELECT ..FOR UPDATE used when huge amount of rows need to be updated?

Its maily used for locking table with differnt node , commely this concpet where used in
ERP products, bcoz different user can acces same table at time and do some DML
operation, using FOR UPDATE will protected ,
before that read this
hb venki

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.
    ;)

  • 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...

  • OpenSQL DataSource not allowed if select-for-update is used Error?

    Hi,
    I have created an enterprise application, EJB (Session + entity) + WAR, and corresponding ear file deployes with the following warning message, I have done similar apps in the past without erros.
    Warning: DataSource TMP_EMPLOYEES_DATA is OpenSQL. It is used by an abstract schema that uses select-for-update locking. It is now allwed to use OpenSQL DataSource if select-for-updaet is used.
    Any idea?
    Thanks

    Hi Ezatullah, all,
    while I do not propose an alternative solution, I'd like to add some explanation to the error message itself: Open SQL for Java strives to provide portable semantics across the set of supported databases and does not offer features which can not be provided by all the databases.
    Now, a SELECT .. FOR UPDATE in the semantics as used here is not generally available, in particular not regarding the locking semantics.
    Thus, the feature is rejected in combination with a Open SQL/JDBC data source.
    Best Regards, Dietmar

  • Should i use SELECT for update NOWAIT ?

    Hi:
    Do I need to use, in my pl/sql triggers and procedures, the SELECT FOR UPDATE NOWAIT sentence, to avoid locks before using update table sentences ? Is it common to use it on stored procedures and triggers?
    Thanks
    Joao Oliveira

    First, what, exactly do you mean by "avoid locks"? I was interpreting that to mean "I want to avoid creating locks in my session that might block someone else", not "I want to avoid having my SELECT wait for locks to be released-- I want it to fail immediately". If you meant the latter, then SELECT ... FOR UPDATE NOWAIT would be what you want. If you meant the former, then pessimistic locking is not what you want.
    Second, what sort of Oracle Forms architecture do you have? Are you still using old-school client-server applications? Or are you using a three-tiered approach? As Tom discusses in that thread, pessimistic locking is only an option when your client application is able to maintain database state across calls (i.e. client/server systems) not when you have stateless connections (which is the norm in the three-tier model). The old client-server versions of Forms would automatically and transparently do pessimistic locking. Since you didn't mention anything about your architecture, most of us probably assumed the more common stateless client architecture (note how Tom's answers progress over the 5 years in that thread as client/server architecture became less and less common).
    Third, while your question is appropriate for either the Database - General forum or the SQL and PL/SQL forum, that generally means that you are free to post it either forum, not that it should be posted in both. The vast majority of the folks that hang out in one forum hang out in the other. It's also rather frustrating to answer a post in one forum only to discover that there is another post in a different forum where someone else had already covered the same points half an hour earlier or to discover that there was additional information in another thread that might have changed your answer.
    Fourth, if you are going to do pessimistic locking, that requires that you are able to maintain state across various database calls, that you are locking on the lowest possible level of granularity, and that you are able to time out sessions relatively aggressively to ensure that someone doesn't open a record, thereby locking it, go to lunch (or have their system die) and then block everyone else from working. Assuming that is the case, and that you have some reasonable way to handle the error that gets generated other than simply retrying the operation, adding NOWAIT is certainly an option. Most applications, particularly those getting written today, cannot guarantee all these things, so pessimistic locking is generally not appropriate there.
    Looking at your other thread (where there is new information that would be useful in this discussion, one of the reasons that multiple threads are generally a bad idea), it seems that you have an ERP application and you are concerned about the performance of entering orders. Obviously, there shouldn't be any locking issues on the ORDER or ORDER_DETAILS tables, assuming that multiple users aren't going to be inserting the same order at the same time. The contention would almost certainly come when multiple orders are trying to update the STOCK and INVENTORY tables, since multiple orders presumably rely on the same rows in those tables. In that case, I'm not sure what adding a NOWAIT would buy you-- unless you were going to roll back the entire order because someone is updating the STOCK row for #2 pencils and your order has an item of #2 pencils, you'd have to keep retrying the operation until you were able to modify the STOCK row, which would be less efficient than just letting that update block until the row was free.
    Now, you could certainly redesign the application to minimize that contention by not trying to update what I assume are aggregate tables like STOCK and INVENTORY directly as part of your OLTP processing or, at least, by minimizing the time that you're locking a row. You could, for example, make STOCK and INVENTORY materialized views rather than tables that refresh ON COMMIT, which should decrease the time that your locks are held. You could also have those tables refreshed asynchronously, which would be even more efficient but may require that you reasses your holdback requirements.
    Justin

  • 'Missing select' error for update statement using WITH clause

    Hi,
    I am getting the below error for update statement using WITH clause
    SQL Error: ORA-00928: missing SELECT keyword
      UPDATE A
      set A.col1 = 'val1'
         where
      A.col2 IN (
      WITH D AS
      SELECT col2 FROM
      (SELECT col2, MIN(datecol) col3 FROM DS
      WHERE <conditions>
        GROUP BY PATIENT) D2
      WHERE
      <conditions on A.col4 and D2.col3>

    Hi,
    The format of a query using WITH is:
    WITH  d  AS
        SELECT  ...  -- sub_query
    SELECT  ...   -- main query
    You don't have a main query.  The keyword FROM has to come immediately after the right ')' that ends the last WITH clause sub-query.
    That explains the problem based on what you posted.  I can't tell if the real problem is in the conditions that you didn't post.
    I hope this answers your question.
    If not, post a complete test script that people can run to re-create the problem and test their ideas.  Include a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    In the case of a DML operation (such as UPDATE) the sample data should show what the tables are like before the DML, and the results will be the contents of the changed table(s) after the DML.
    Explain, using specific examples, how you get those results from that data.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • I am updating iphoto 9.1 to 9.3 and every time when I clicked for update aps store asked to open it in the account where you purchased. I am using the same account and its available in the purchased item of this account. Can someone resolve this problem.

    I am updating iphoto 9.1 to 9.3 and every time when I clicked for update aps store asked to open it in the account where you purchased. I am using the same account and its available in the purchased item of this account. But in my purchased item library it indicates that you update iPhoto. I am not sure which account the aps store asking. Can someone resolve this problem.

    Contact App Store support. They're the folks who can help with Account issues.
    Regards
    TD

  • HT4972 I'm trying to update my iphone 3G to ios5 - however in Itunes when I 'check for updates' it is advising me that I have the latest version (4.2.1). Hence I can't update and now I can't run a few of the apps I previously used. Help!

    Following a backup and restore of my iphone 3g I have lost the use of a number of apps - this seems to be as they need ios5 or later to support them and I only have 4.2.1
    When I check for updates via itunes I am advised that I have the latest version - but clearly I don't.
    Any help gratefully received on how I can upgrade to ios5
    Yally

    Sadly, the iPhone 3G can not be upgraded beyond iOS 4.2.1.

  • Performance of using a Select For Update vs a correlated subquery

    I was wondering wether or not it is more effecient to use the
    Select ... For Update (with a cursor etc.) versus a correlated
    subquery.
    I can accomplish the same thing with either however performance
    at our site is an issue.

    Use select for update cursor as that is faster as it updates
    based on the rowid. One thing to keep in mind is that rowid is
    session specific and the rows to be updated get locked so that
    nobody else can update them till the lock is released. I have
    had very good performance results with these cursors.
    Good luck !
    Sudha

  • 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.

  • 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

  • "All of the Playlists Selected for Updating No Longer Exist"

    My family has 2 ipod shuffles. After purchasing a Nano recently, I inserted the cd that came with it. Apparently the existing iTunes software was removed and reinstalled. At any rate, the library still shows all the original songs, but when the Nano is plugged in, iTunes immediately gives a prompt stating "Songs on the iPod *** cannot be updated because all of the playlists selected for updating no longer exist." The library is there, the playlists that were there are there, and I can play the songs on my cpu. Is there anything I can do besides completely uninstalling everything and starting over?
    iPod Nano   Windows XP Pro  

    This user tip should help you sort out your missing playlist problem: Hudgie - iPod cannot sync because one or more playlists are missing

  • Difference in select for update of - in Oracle Database 10g and 11g

    Hi, I found out that Oracle Database 10g and 11g treat the following PL/SQL block differently (I am using scott schema for convenience):
    DECLARE
      v_ename bonus.ename%TYPE;
    BEGIN
      SELECT b.ename
        INTO v_ename
        FROM bonus b
        JOIN emp e ON b.ename = e.ename
        JOIN dept d ON d.deptno = e.deptno
       WHERE b.ename = 'Scott'
         FOR UPDATE OF b.ename;
    END;
    /While in 10g (10.2) this code ends successfully (well NO_DATA_FOUND exception is raised but that is expected), in 11g (11.2) it raises exception "column ambiguously defined". And that is definitely not expected. It seems like it does not take into account table alias because I found out that when I change the column in FOR UPDATE OF e.empno (also does not work) to e.mgr (which is unique) it starts working. So is this some error in 11g? Any thoughts?
    Edited by: Libor Nenadál on 29.4.2010 21:46
    It seems that my question was answered here - http://stackoverflow.com/questions/2736426/difference-in-select-for-update-of-in-oracle-database-10g-and-11g

    The behaviour seems like it really is a bug and can be avoided using non-ANSI syntax. (It makes me wonder why Oracle maintains two query languages while dumb me thinks that this is just a preprocessor matter and query engine could be the same).

  • HT201232 My operating system is Mac OS X 10.6.8 and when I'm surfing the web, it tells me I need to update my browser however when I check for updates, nothing comes up. What do I need to do to get Mac OS X Lion v10.7?

    My operating system is Mac OS X 10.6.8 and when I'm surfing the web, it tells me I need to update my browser however when I check for updates, nothing comes up. What do I need to do to get Mac OS X Lion v10.7?

    Software update will only bring you up to the current level of the system you are using - you are at the maximum for Snow Leopard. To get Lion or higher you will have to go to the Mac App Store in Applications and purchase it there (Yosemite is free). You will need to check that your Mac meets the requirements and you should particularly note that PPC programs such as AppleWorks will not run in Lion or above.
    The requirements for Lion are:
    Mac computer with an Intel Core 2 Duo, Core i3, Core i5, Core i7, or Xeon processor
    2GB of memory
    OS X v10.6.6 or later (v10.6.8 recommended)
    7GB of available space
    Lion is available in the Online Apple Store ($19.99). Mountain Lion (10.8.x) is also available there at the same price (though it's reported to have been removed from sale in some countries so may well cease to be available generally) but there seems little point as the system requirements are the same for Yosemite (10.10.x) - which is free - unless you need to run specific software which will run on Mountain Lion only.
    The requirements for Mountain Lion and Yosemite are:
    OS X v10.6.8 or later
    2GB of memory
    8GB of available space
      and the supported models are:
    iMac (Mid 2007 or newer)
    MacBook (Late 2008 Aluminum, or Early 2009 or newer)
    MacBook Pro (Mid/Late 2007 or newer)
    Xserve (Early 2009)
    MacBook Air (Late 2008 or newer)
    Mac mini (Early 2009 or newer)
    Mac Pro (Early 2008 or newer)
    Yosemite is available from the Mac App Store (in Applications). Mountain Lion can be obtained the Online Apple Store. (Mavericks is no longer available.)
    If the problem is only with Safari and you are otherwise happy with Snow Leopard you could switch to FireFox (free) - the latest version of that will run in Snow Leopard.

  • 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.

Maybe you are looking for