?
Solved

selecting first and last records from a result set

Posted on 2002-05-13
7
Medium Priority
?
1,902 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 143

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 143

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
Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

 
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 400 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

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

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

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
In this blog post, we’ll look at how using thread_statistics can cause high memory usage.
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…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

762 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