Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I limit the number of recordsets returned?

Status
Not open for further replies.

no137

Programmer
Feb 5, 2002
7
US
Newbie Question:
How can I limit the number of recordsets returned from a select statement like "select * from table"? I only want the first 50 records.

Thanks
Fred
 
sounds like the "top n" problem

since this is the ansi sql forum, i shall give the ansi sql solution first

Code:
select foo
     , bar 
  from yourtable xxx
 where 50 >
       ( select count(*)
           from yourtable
          where bar > xxx.bar
       )
order by bar desc

if you have mysql or postgresql, use this instead --

Code:
select foo
     , bar
  from yourtable
order by bar desc
 limit 50

if you have microsoft sql/server or access, use this instead --

Code:
select top 50
     , foo
     , bar
  from yourtable
order by bar desc

there are solutions for oracle and db2, holler if you need them

rudy
 
Just what to point out that the solution

Code:
select foo
     , bar 
  from yourtable xxx
 where 50 >
       ( select count(*)
           from yourtable
          where bar > xxx.bar
       )
order by bar desc

is a performance killer (in most RDBMS).

The normal standard SQL solution to this is programming the search and just fetching the first 50 rows.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top