Oracle Skip Locked

Oracle 11g introduced SKIP LOCKED clause to query the records from the table which are not locked in any other active session of the database.

This looks quite similar to exclusive mode of locking.

oracle-skip-locked

The select for update statement has always been problematic for large updates because it the default is to wait for locks and using select for update other tasks can abort waiting on access with the ORA-300036 error:

ORA-30006: resource busy; acquire with WAIT timeout expired

In other cases using select for update with the nowait clause you your own update may abort with the ORA-00054 error:

ORA-00054 resource busy and NOWAIT specified

Even worse, if a select for update task aborts, a zombie process may hold the row locks long term, requiring DBA intervention.

To illustrate, we open two sessions. In the first session, we lock the row with deptno as 10 using FOR UPDATE NOWAIT.

SELECT *
  FROM dept  WHERE
 deptno = 10
FOR UPDATE NOWAIT;

Output:

DEPTNO     DNAME          LOC
---------- -------------- -------------
10         ACCOUNTING     NEW YORK

In the second session, we try to lock two rows (deptno 10 and 20) from the table dept using FOR UPDATE NOWAIT. An exception is thrown after executing the following statement because one of the row (i.e. deptno 10) out of the selected list is already locked by session 1.

SELECT * FROM dept
 WHERE deptno IN (10,20)
FOR UPDATE NOWAIT;

Output:

SELECT * FROM dept WHERE deptno IN (10,20)
FOR UPDATE NOWAIT
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified

Now we again try to lock two rows (deptno(s) 10 and 20) from the table dept but using the clause FOR UPDATE SKIP LOCKED instead of FOR UPDATE NOWAIT. As you can see the following statement has:

  1. returned the control without throwing an exception
  2. acquired lock on the row (i.e. deptno 20) which is available for locking
  3. skipped the row (i.e. deptno 10) that has been locked already by session 1
SELECT * FROM dept
 WHERE deptno IN (10,20)
FOR UPDATE SKIP LOCKED;

Output:

DEPTNO     DNAME          LOC
---------- -------------- -------------
20         RESEARCH       DALLAS


One Comment

  • jong jin 6 January, 2014, 13:20

    thank you for your post,
    I will quote. thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *