Sorry, yes, you are right. It is still incorrectly done even to return a single row. Rownum doesn't work as it's being used (it assigns the row numbers to the results themselves so you can't actually ask for rownum = 50 - unless you include rownum in the inner query). You can compare rownum, however as it'll check that as it's building results. It makes sense if you think about it (however obtuse) - it will make the rownum test (in the absolute case rownum = 50) and it will fail, hence you'll never get/generate any rows (if you use absolute). However, if you use <= some number, it'll succeed until it tries to generate a row past your range.
The problem query again:
Code:
SELECT * FROM (SELECT E.JOB_EXECUTION_ID AS SORT_KEY FROM BATCH_JOB_EXECUTION E, BATCH_JOB_INSTANCE I WHERE E.JOB_INSTANCE_ID=I.JOB_INSTANCE_ID ORDER BY E.JOB_EXECUTION_ID DESC) where rownum = 20;
One possible fix (include rownum in the inner query):
Code:
SELECT SORT_KEY FROM (SELECT E.JOB_EXECUTION_ID AS SORT_KEY, rownum rn FROM BATCH_JOB_EXECUTION E, BATCH_JOB_INSTANCE I WHERE E.JOB_INSTANCE_ID=I.JOB_INSTANCE_ID and rownum <= 20 ORDER BY E.JOB_EXECUTION_ID DESC) WHERE rn = 20;
Option 2 - Use min() over over the results to snag the sort key:
Code:
SELECT min(sort_key)
FROM (select E.JOB_EXECUTION_ID AS SORT_KEY FROM BATCH_JOB_EXECUTION E, BATCH_JOB_INSTANCE I
WHERE E.JOB_INSTANCE_ID=I.JOB_INSTANCE_ID ORDER BY E.JOB_EXECUTION_ID DESC)
WHERE ROWNUM <= 20;