I have a query in Oracle where I need to:
Order the entire table by a specific column. Select and lock a certain number of rows using SELECT FOR UPDATE. However, the issue is that Oracle first selects the rows in an arbitrary order and then applies ORDER BY only to the selected subset. This results in the final ordering being applied after selection rather than before.
What I Tried Since FETCH does not work with SELECT FOR UPDATE, I used ROWNUM to limit the number of rows. However, the ordering is still applied after row selection, not before. Expected Behavior I want the query to first sort the entire table, then select and lock the top N rows in that order.
Actual Behavior The query selects N rows arbitrarily, then applies ORDER BY only to those rows.
Note: Common Table Expressions (CTEs) and inline queries do not work with SELECT FOR UPDATE, so I cannot use them to enforce ordering before selection.
How can I ensure that the selection happens after ordering the entire table while still using SELECT FOR UPDATE?
Any suggestions or workarounds would be appreciated!
Have you tried: (you should specify which version you are using...)
SELECT * FROM table
WHERE pk IN (
SELECT pk FROM table
ORDER BY ...
FETCH FIRST n ROWS ONLY
)
-- opt. ORDER BY ...
FOR UPDATE ;