简体   繁体   中英

Getting Top 5 Results using ROWNUM in Oracle

is there something wrong with my query? I use below to get the first 5 results ordered by AUDIT_ACTN then AUDIT_STAMP.

SELECT * FROM (SELECT * FROM TABLE_SAMPLE ORDER BY AUDIT_ACTN  
ASC,AUDIT_STAMP ASC)
WHERE ROWNUM <= 5

And I use this to check if I'm getting the correct rows.

SELECT * FROM TABLE_SAMPLE  ORDER BY 
AUDIT_ACTN,AUDIT_STAMP

The problem is the top 5 rows of the 2nd query is slightly different with the result of the 1st query. Only 3 rows are the same and with my observation the other 2 are the rownum1 & 2 of the 2nd query. I hope you understood my question I really need help.Thanks!

I remember reading that ORDER BY would not be guaranteed with subqueries, but here is an alternative solution using ROW_NUMBER -- this includes the ORDER BY in it's OVER clause:

SELECT * FROM 
(SELECT Field1, Field2, ROW_NUMBER() OVER (ORDER BY Field2,Field1) AS RN 
 FROM TABLE_SAMPLE 
 ) t 
WHERE RN <= 5

And here is the Fiddle .

And here is some documentation about Oracle, subqueries, and ORDER BY:

http://docs.oracle.com/javadb/10.8.2.2/ref/rrefsqlj13658.html

In subqueries, the ORDER BY clause is meaningless unless it is accompanied by one or both of the result offset and fetch first clauses or in conjunction with the ROW_NUMBER function, since there is no guarantee that the order is retained in the outer result set. It is permissible to combine ORDER BY on the outer query with ORDER BY in subqueries.

Good luck.

Try this:This query return top 5 record .

 SELECT * FROM 
    (SELECT Field1, Field2, rank() OVER (ORDER BY Field1,Field2) AS rank
     FROM TABLE_SAMPLE 
     ) t 
    WHERE t.rank <= 5

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