Solved

selecting first and last records from a result set

Posted on 2002-05-13
7
1,849 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]
Comment Utility
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
Comment Utility
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]
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 22

Expert Comment

by:DrSQL
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction: I have seen many questions on EE and elsewhere, asking about how to find either gaps in lists of numbers (id field, usually) ranges of values or dates overlapping date ranges combined date ranges I thought it would be a good …
This article explains all about SQL Server Piecemeal Restore with examples in step by step manner.
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…

744 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

15 Experts available now in Live!

Get 1:1 Help Now