[web] SQL, return only the second result?

Started by
4 comments, last by konForce 17 years, 10 months ago
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
Advertisement
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
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.
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.
thx, im using sql server
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.

This topic is closed to new replies.

Advertisement