In Oracle there is no limit, so I used this:
SELECT *
FROM (
SELECT m.*, ROWNUM r
FROM TABLE_NAME m
WHERE COL LIKE XYZ
ORDER BY ID ASC
)
WHERE r BETWEEN 10 AND 20;
But it is still not ordered. It is ordered in the 10 from 20, but not the entire table. How can I do that?
I want to ORDER THE ENTIRE TABLE with WHERE clause and get the ranged ones. The solution above only order within the range.
Maybe less confusing solution (in case anyone googled here):
SELECT a.* from (
SELECT b.*, ROWNUM r FROM (
SELECT * FROM table ORDER BY id ASC
) b WHERE (city LIKE '%abc%' OR city IS NULL)
) a where r between 5 and 10
So it is a better idea to put order right in the middle criteria, and then put other criteria in the second level, and put row number in the outter-most level.
You’ll need one more level of nesting as far as I know, something like:
Demo:
rownumgets “materialized” before the ordering, so your approach cannot work, as you’ve noticed:So nest it once to get row numbers after ordering:
But you can’t do a
betweenwith this though:This is because
rownumgets a value only once a row enters the result set.And add a second layer to remove the first lines: