简体   繁体   中英

Order by not working in Oracle subquery

I'm trying to return 7 events from a table, from todays date, and have them in date order:

SELECT ID
FROM table
 where ID in (select ID from table
where DATEFIELD >= trunc(sysdate)
order by DATEFIELD ASC)
and rownum <= 7

If I remove the 'order by' it returns the IDs just fine and the query works, but it's not in the right order. Would appreciate any help with this since I can't seem to figure out what I'm doing wrong!

(edit) for clarification, I was using this before, and the order returned was really out:

select ID
from TABLE
where DATEFIELD >= trunc(sysdate)
and rownum <= 7
order by DATEFIELD 

Thanks

The values for the ROWNUM "function" are applied before the ORDER BY is processed. That why it doesn't work the way you used it ( See the manual for a similar explanation)

When limiting a query using ROWNUM and an ORDER BY is involved, the ordering must be done in an inner select and the limit must be applied in the outer select:

select *
from (
  select *
  from table
  where datefield >= trunc(sysdate)
  order by datefield ASC
)
where rownum <= 7
  1. You cannot use order by in where id in (select id from ...) kind of subquery. It wouldn't make sense anyway. This condition only checks if id is in subquery. If it affects the order of output, it's only incidental. With different data query execution plan might be different and output order would be different as well. Use explicit order by at the end of the main query.

  2. It is well known 'feature' of Oracle that rownum doesn't play nice with order by . See http://www.adp-gmbh.ch/ora/sql/examples/first_rows.html for more information. In your case you should use something like:

     SELECT ID FROM (select ID, row_number() over (order by DATEFIELD ) r from table where DATEFIELD >= trunc(sysdate)) WHERE r <= 7 

See also:

See also other similar questions on SO, eg.:

Your outer query cant "see" the ORDER in the inner query and in this case the order in the inner doesn't make sense because it (the inner) is only being used to create a subset of data that will be used on the WHERE of the outer one, so the order of this subset doesn't matter.

maybe if you explain better what you want to do, we can help you

ORDER BY CLAUSE IN Subqueries : the order by clause is not allowed inside a subquery, with the exception of the inline views. If attempt to include an ORDER BY clause, you receive an error message

An inline View is a query at the from clause.

SELECT t.* FROM (SELECT id, name FROM student) t

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