sql select * between exact number of rows

I don't know of a general way.. but each DB has a way. For example in oracle you can do it with a nested select

Oracle:

select * from (
select a, b, c from table_foo
where id = 124
)
WHERE rownum >= 235
and ROWNUM <= 250

MSSQL

select * from 
    (select Row_Number() over 
     (order by userID) as RowIndex, * from users) as Sub
    Where Sub.RowIndex >= 235 and Sub.RowIndex <= 250

MySQL

SELECT * FROM TableName LIMIT 235, 15

If your using mySQL you could use the limit command for example:

SELECT * FROM TableName LIMIT 235, 15

Where the first number is the start index and the second is the number of rows to return.


This can be done very easily in SQL Server 2012. By using the new feature of OFFSET and FETCH. This will help you to pull out desired rows in an already ordered/sorted result set.

Please see the below example:

SELECT
             PP.FirstName + ' ' + PP.LastName AS 'Name'
            ,PA.City
            ,PA.PostalCode
FROM  Person.Address PA
            INNER JOIN
                        Person.BusinessEntityAddress PBEA
                                    ON PA.AddressID = PBEA.AddressID 
            INNER JOIN
                       Person.Person PP
                                    ON PBEA.BusinessEntityID = PP.BusinessEntityID
ORDER BY PP.FirstName
            OFFSET 0 ROWS
                FETCH NEXT 5 ROWS ONLY

Please notice the OFFSET 0 and FETCH NEXT 5 written above.
This is will display only 5 rows starting from 0 the row.

Tags:

Database

Sql