Oracle Tip: Apply RowNum after Order By

January 22, 2010 by Reboot · Leave a Comment 

Ordering a resultset which contains a rownum statement will order the resultset which is return by the rownum.

e.g. the query:

select * from mytable where rownum <= 10 order by id desc

does not have to return the last 10 records.

See also:
http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html

Think of it as being processed in this order:
1. The FROM/WHERE clause goes first.
2. ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.
3. SELECT is applied.
4. GROUP BY is applied.
5. HAVING is applied.
6. ORDER BY is applied.