Solved

selecting first and last records from a result set

Posted on 2002-05-13
7
1,897 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
Webinar: Security & Encryption in the MySQL world

Join Percona’s Solutions Engineer, Dimitri Vanoverbeke as he presents “Security and Encryption in the MySQL world” on Thursday, July 6, 2017 at 7:00 am PDT / 10:00 am EDT (UTC-7).

 
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

Enroll in June's Course of the Month

June’s Course of the Month is now available! Experts Exchange’s Premium Members, Team Accounts, and Qualified Experts have access to a complimentary course each month as part of their membership—an extra way to sharpen your skills and increase training.

Question has a verified solution.

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

These days, all we hear about hacktivists took down so and so websites and retrieved thousands of user’s data. One of the techniques to get unauthorized access to database is by performing SQL injection. This article is quite lengthy which gives bas…
This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
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…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…

726 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