Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.server -> Re: Can I use an index to get the last n records?

Re: Can I use an index to get the last n records?

From: John K. Hinsdale <hin_at_alma.com>
Date: Mon, 16 Jul 2007 09:07:33 -0700
Message-ID: <1184602053.972654.318030@d55g2000hsg.googlegroups.com>


On Jul 16, 11:00 am, Timasmith <timasm..._at_hotmail.com> wrote:
> I want to execute something like this (which doesnt work at all)
>
> select * from sales
> where sales_person_id = :sales_person_param
> and rownum < 10
> order by sales_date_time desc

Oracle "assigns" the psuedo-column ROWNUM before any ordering is done. However you can wrap the ordered query in a subquery, then apply
the ROWNUM filter afterward:

select * from (
  select * from sales
  where sales_person_id = :sales_person_param   order by sales_date_time desc
)
where rownum <= 10

Note that if you display the ROWNUM as part of the results, any "ties" will be incorrectly assigned different ranks. To handle that, use the RANK() analytic in the subquery, which will handle ties appropriately. Probably not a big deal for this particular case thought.

[On an un-related note, some consider "SELECT *" to be ill-advised practice from within an appliction, because it breaks when columns are added, dropped or renamed, plus it relies on an (unreliable) ordering of columns returned]

HTH,
John Hinsdale Received on Mon Jul 16 2007 - 11:07:33 CDT

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US