[web] SQL, return only the second result?

This topic is 4250 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi I was wondering if it was possible to return a specific result row, eg if i had: select * from table I only need the second result, is there a way of getting it? thanks

Share on other sites
I know a really really nasty hack way. that degrads in performance badly as the numbers rise:

something along the lines of

select top 1 * from table and pkcolumn not in (select top 1 pkcolumn from table)

this general trick works for paging, such as selecting the first 10, second 10, third 10, etc. But really doesn't scale well at all (and uses subselects which many browers don't use).

select top 10 * from table and pkcolumn not in (select top 20 pkcolumn from table)

would get the 3rd page of 10.

There are other methods that are more gereral purpose sql, such as temp tables, but it's really just easier to do this sort of thing in code anyway.

In fact, I solved this paging problem using the above, but replaced it in less than 1 week because it just isn't the best way to go.

To do that, simply do something like

select top 100 pkcolumn from table

pick the number of rows (100 in the example) based on what you are trying to do

in code, then select the row / rows you want

Share on other sites
Not the row number... but there are certain options.

Such as :

select top 1 * from table

or

select max(value) from table

...

OR

select * from table where key = (value to 2nd row key)

These are what you have to work with.

Share on other sites
You didn't say what kind of DB you are using.

For MySQL it's limit, offset:
select * from table limit 1 offset 1

the query above would return only the second row from table.
Whatever DB you are using - you should read it's documentation about SELECT syntax.

Share on other sites
thx, im using sql server

Share on other sites
The general case for MS-SQL:
SELECT * FROM (  SELECT TOP n * FROM (    SELECT TOP x col1,col2,col3    FROM tbl    ORDER BY id ASC  ) AS a ORDER BY id DESC ) AS b ORDER BY id ASC

n is how many rows you want to get
x is the number of rows to skip PLUS n.

Examples:
* to only get the 2nd row: n=1, x=2
* to get rows 11 to 20: n = 10, x = 20

You need to reverse all three of the ASC/DESC to switch the order.

Usually, it's better to do things in the database. For example, grabbing 1000 records and looping through them all just to get 10 is a waste. But always run benchmarks on critical areas of your application to determine which method is best for you.