How to Skip Top N Rows in SQL Server? – Interview Question of the Week #237

Question: How do you skip the first N rows and return the rest? Use ORDER BY with OFFSET N ROWS. FETCH is optional.

The first group of towels is set aside while the remaining sequence stays on its shelf

I asked this in an interview and heard solutions using ranking functions, temporary tables, CTEs and subqueries. Nobody mentioned OFFSET. Those alternatives can work, but this particular requirement has a very short answer from SQL Server 2012 onward.

SELECT *
FROM AdventureWorks2025.Person.Address
ORDER BY AddressID
OFFSET 100 ROWS;

-- Return just the next page instead of every remaining row.
SELECT AddressID, AddressLine1
FROM AdventureWorks2025.Person.Address
ORDER BY AddressID
OFFSET 100 ROWS FETCH NEXT 10 ROWS ONLY;

The first query is the original AdventureWorks Address example, with the installed sample database name updated. It skips 100 rows in AddressID order, then returns every remaining row. The second adds a ten-row page. OFFSET is a row count, not a test that AddressID is greater than 100: gaps in IDs don’t change that distinction.

Use a unique ordering, such as the AddressID key, so ties don’t make the selected boundary arbitrary. Separate requests can still move rows between pages if the underlying data changes.

I like the simplicity of this syntax, but it is not always faster than every alternative. A large offset can require reading and discarding many earlier rows. For deep paging, compare the plan and I/O with a key-based continuation method when the application permits it.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Ranking Functions, SQL Function, SQL Paging, SQL Scripts, SQL Server
Previous Post
How to Write in Text File from T-SQL in SQL Server? – Interview Question of the Week #236
Next Post
How to Create a Table Automatically in All Newly Created Databases? – Interview Question of the Week #238

Related Posts

1 Comment. Leave new

  • Hi Pinal, OFFSET and FETCH are a good solution but just for small number of records. When you are working with a lot off records the performance decrease when the @PageNumber is higher than 100.
    In this case, how can I solve the problem related to slow query answer whan I try to go into @pagenumbers up to 100?
    Best regards

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.