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: <fitzjarrell_at_cox.net>
Date: Mon, 16 Jul 2007 09:36:40 -0700
Message-ID: <1184603800.692038.259090@o61g2000hsh.googlegroups.com>


On Jul 16, 10:00 am, Timasmith <timasm..._at_hotmail.com> wrote:
> If I have a table with 100,000,000 rows
>
> sales(sales_id, sales_person_id, sales_date_time, ...)
>
> create index sales_date_index on sales (sales_person_id,
> sales_date_time);
>
> 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
>
> I want it to use my sales_date_index to read just 10 indexed records -
> NOT read all records for the sales_person_id, sort in memory and then
> return me the result set.
>
> Anyway in general I can force traversal of the records using an index?
>
> thanks

Obviously this 'doesn't work', and this has been discussed numerous times before in this newsgroup. Since searching the archives is apparently not to your liking:

The 'problem' with your original query is that you don't fully comprehend HOW rownum is assigned; it's assigned as the rows are returned, not after they are ordered. To get past that one must do this:

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

Now your rownum values will be assigned to the ordered result set of the imbedded query. Of course since your index is non-unique and the date is the second column in your index I doubt very seriously it would help in the ordering of your results. The above query, though, should return the results you expect.

David Fitzjarrell Received on Mon Jul 16 2007 - 11:36:40 CDT

Original text of this message

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