I am writing a query to give the next 5 smallest items greater than a value, which is the primary key (e.g. 101). Id is char(19) in this case and Id is the clustered index.
My attempt at the query is as follows:
SELECT *
(SELECT *
(SELECT * FROM
PERSON
ORDER BY ID)
WHERE ID >= '101')
WHERE rownum <= 5
I want to guarantee that the 5 results returned are the 5 biggest ids in table greater than 101, rather than the 5 biggest results that are encountered first. Hence I added an Order by into the query. I know the rownum is assigned after the where clause but before the order by is executed.
Is my query/logic correct? Do I require the order by clause to be there?
You need the order by but descending if you want the 5 biggest. You can also merge the two inner queries:
If you actually meant the 5 smallest IDs bigger than 100 then stick with ascending.
Doing greater than on a character field containing numbers, may not be doing what you expect, it will be doing an alphabetic order rather than a numeric order. So 201 will be bigger than 1000000.
Example of weird ordering
If you want numeric comparison then change the where filter to be
To_Number(ID) >= 101(or better still change the column to be a numeric type)