How to select between the top 50 and 100 returned (queried) rows in sql?

Issue

Using MSSQL, how can I skip the first set of 50 records, return the next set of 50, and exclude any remaining records from a query. Essentially, something like what one would imagine the following code would do where identitynumber is the identity of the record.

SELECT TOP(100) * FROM dbo.users
WHERE users.name = 'John' AND IDENTITYNUMBER >=50 AND IDENTITYNUMBER <=100

Solution

Guess you need the OFFSET keyword.

SELECT employee_id, first_name, last_name, salary 
FROM employees 
ORDER BY salary DESC 
OFFSET 5 ROWS 
FETCH NEXT 5 ROWS ONLY;

Or in your case:

select * from dbo.Users
where name = 'John'
order by users.name
offset 50 rows
fetch next 50 rows only;

Source: https://www.sqltutorial.org/sql-fetch/

Answered By – Svein Terje Gaup

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.