Solved

selecting first and last records from a result set

Posted on 2002-05-13
7
1,864 Views
Last Modified: 2011-08-18
how do i select top x , bottom x rows in a select query.

i mean something like
select * from <blah blah> where <blah blah> first 10;

 
select * from <blah blah> where <blah blah> last 10;

0
Comment
Question by:k_suchdeva
  • 3
  • 2
  • 2
7 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7006147
This depends largely from the database system you are using. Anyway, when you say "first" and "last", you also need to specify the "ordering".

Here is the suggestion for SQL Server:
select top 10 * from yourtable order by somefield asc
union all
select top 10 * from yourtable order by somefield desc

or
set rowcount 10
select * from yourtable order by somefield asc
union all
select * from yourtable order by somefield desc
set rowcount 0

CHeers
0
 
LVL 2

Author Comment

by:k_suchdeva
ID: 7006261
I have tried these two already.
SOrry forgot to mention my datbaase is oracle and i am trying it from sqlplus.
select top 10 * from <table>;
select top 10 * from <table>
           *
ERROR at line 1:
ORA-00923: FROM keyword not found where expected


set rowcount 10
SP2-0158: unknown SET option "rowcount"

0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 7006305
Check out this:

select * from yourtable where rownum <=10 order by somefield asc

select * from yourtable where rownum <=10 order by somefield desc

!!!! UNTESTED !!!!
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 22

Expert Comment

by:DrSQL
ID: 7006889
k_suchdeva,
   As long as you are on Oracle 8i or later, you can use the analytic functions (angelll's solution won't work since rownum is assigned prior to the sort):

Top 10:
select * from
  (select <blah column 1>, <blah column 2>, <etc.>,
          row_number() over (order by <blah col 1>,
                                           <blah col2>) ranking
     from <blah blah>)
 where ranking <= 10;

Bottom 10 (just reverse the order by):
select * from
  (select <blah column 1>, <blah column 2>, <etc.>,
          row_number() over (order by <blah col 1> desc,
                                           <blah col2> desc) ranking
     from <blah blah>)
 where ranking <= 10;

you can also sort the whole thing (takes longer) instead of using these functions, and put it in an inline view:

select * from (select * from <blah blah> order by <blah columns>)
 where rownum <= 10;

and the reverse (putting desc on the columns in the order by) for the bottom 10.

Good luck!
0
 
LVL 2

Author Comment

by:k_suchdeva
ID: 7016157
Strangely

select * from mr_orders where rownum <=1;
works
while
select * from mr_orders where ranking <=1;
does not

So who wants the points ?
0
 
LVL 22

Accepted Solution

by:
DrSQL earned 100 total points
ID: 7016361
k_suchdeva,
    rownum is what's called a "virtual column" that is available to any query as if it was a part of the table being queried (USER and SYSDATE are other examples).  "Ranking" is a column alias that I gave to the row_number function inside the inline view (the select that is inside the parens), so that I could refer to it in the outer query.  I could have called it fred or barney, I just used a name that indicated what it was doing.  That means you can't use "ranking" without the inline view.  So:

select * from
(select ename,sal,row_number() over (order by sal desc) as fred
   from emp)
where fred <= 5;

Will get me the top 5 salaries and:

select * from
(select ename,sal,row_number() over (order by sal) as barney
   from emp)
where barney <= 5;

Will get me the bottom 5.

But, "select * from mr_orders where rownum <=10" will just give me the first 10 received from the mr_orders table.  And:

select * from mr_orders where rownum <=10 order by qty;

Will still give me the first 10, not the top 10.  This is because sorting happens after the result set has been completed, but rownum is assigned as records are added to the result set.  So, to get the top 10 customers (based on number of orders):

select * from
(select custid,count(*) orders,
           row_number() over (order by count(*) desc) ranking
    from mr_orders
   group by custid)
where ranking <= 10;

Good luck!

0
 
LVL 2

Author Comment

by:k_suchdeva
ID: 7016389
Hi DrSQL
Got it !!
This is one thing i love so much about this site.

People are just passionate about explaining the problem and you get you get exactly the answer you want.

Thanks for ur effort.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now