Discussion Locked

MS-SQL

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Is it possible to select a particular number of rows from a table (assuming that the table does not has any Identity) without any "where" condition.
(for eg. cosider a table containing 100 rows and If I want to select first 10 records,we can use "select top 10 * from table_name"
Similarly,If I want to take the records between 50 and 60, What should I do?)

(If sub-Queries are used,It should not select the whole records from the table.)

6 replies

by kevin.riggs

How about:

SELECT TOP 10 * FROM (
SELECT TOP 60 * FROM table_name ORDER BY fieldname DESC) DESC

The first select statement (SELECT TOP 60 * FROM table_name ORDER BY fieldname DESC) will yield a set of 60 records in DESCending order. The second select statement (SELECT TOP 10 * FROM () DESC) will reverse the order of the last 10 records in the first set so that the first record will be number 51, the second will be record 52, the third will be number 53 and so on. You could simplify this with a stored procedure that accepts the number to start with and the number of records you want and then it builds a select statement so that you could always call the select statement passing it the first number you want (in this case number 51) and the total number of records (in this case 10) and the result would return records 51-60.

by kamalakannans

Thank u Mr.Kevin !
I tried it before itself.I gave 100 records for example only.If I have 1 lakh records and If I want to fetch records between 50000 and 51000,I should fetch either first 51000 records or last 50000 records.Here I am unnecessarily fethchig 50000(approx.) to fetch a few records.
So,If there is any other possible way,please notify it.

by lo

If there is not select data, I think there is a way to select on the record number. Not sure if/how (not that knowlegable about SQL). If there isn't a record number you can add a field that is a record count 1, 2, 3, ..., auto increent or load thefield yourself. That will give you a means of selecting. As I remember auto-increment and possibly the record number may have holes from deleted records. lo

This discussion is closed to new replies.