0

I have a table in my database containing about 100000 records. I have to select 10 records from it by row number from n to n+10. I have used following way to get records-

ALTER PROCEDURE getGalleryImagesByPaging
@startIndex int,
@endIndex int
AS
  BEGIN
  WITH gallery as(
   Select ImageId,Caption, ROW_NUMBER() over (Order by id desc) as RN from   imagegalleries where ishome=1 and IsActive=1 
)
Select ImageId, Caption From gallery Where RN Between @startIndex AND @endIndex;
  END
GO

but I think it is very expensive query because it selects all the elements first then select records by row number. Please suggest me the better way to do it.

5

1 Answer 1

1

You can also use OFFSET FETCH to get your desire output in Sql server 2012 and +

ALTER PROCEDURE getGalleryImagesByPaging
@startIndex int,
@endIndex int
AS
BEGIN
Select ImageId,
       Caption 
       from   imagegalleries 
       where ishome=1 and IsActive=1 
       ORDER BY id desc OFFSET @startIndex ROWS FETCH NEXT @endIndex ROWS ONLY
END
GO

Limitations in Using OFFSET-FETCH

  • ORDER BY is mandatory to use OFFSET and FETCH clause.
  • OFFSET clause is mandatory with FETCH. You can never use, ORDER BY … FETCH.
  • TOP cannot be combined with OFFSET and FETCH in the same query expression.
  • The OFFSET/FETCH rowcount expression can be any arithmetic, constant, or parameter expression that will return an integer value. The rowcount expression does not support scalar sub-queries.

Reference: MSDN => OFFSET and FETCH

Sign up to request clarification or add additional context in comments.

1 Comment

Do mention that it will work with Sql server 2012+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.