简体   繁体   中英

Oracle SQL: possibility of a query that combines SELECT FOR UPDATE SKIP LOCKED with ordering and rownum limit

From what I understand, the answer, broadly speaking is "no", but here's the problem:

I need to run a query that needs to do the following things:

  1. Select rows in a table, sorted by a column
  2. Of these rows, pick and lock the first one, skipping other locked rows.

An example query would look something like this:

SELECT
    E.*
FROM
   polled_table E
WHERE 
    E.ID IN 
    (SELECT ID FROM
        (SELECT 
            ID
         FROM
            polled_table
         WHERE 
            condition = 'value'
         ORDER BY priority DESC)
     WHERE rownum < 2)
FOR UPDATE SKIP LOCKED;

This of course doesn't work in the sense that the skip locked essentially doesn't work as that part of the query only ever sees one row.

Bringing the "rownum < 2" outside doesn't seem to be possible (it triggers errors described for example here: ORA-00907 Missing right parenthesis issue - select with order by inside insert query )

I've tried several combinations, but they either don't do what I want or they straight up generate errors. The only thing that might work would be removing the rownum condition, but that would lock a large number of rows.

At this point, as I mentioned, I'm thinking it just be done, not as a single query at least.

If you push the query into a cursor, then just fetch the first row. That should accomplish this task with the skip locked intact.

Something like (I'm away from my DB so pardon any minor syntax errors):

Cursor C is SELECT
    E.*
FROM
   polled_table E
WHERE
    E.ID IN
    (SELECT ID FROM
        (SELECT
            ID
         FROM
            polled_table
         WHERE
            condition = 'value'
         ORDER BY priority DESC))  for update skip locked;

var c%rowtype;

Open C
Fetch C into var;
close C;

Then process that first row fetched in the VAR variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM