LINQ to SQL : Paging Data

LINQ to SQL : Paging Data

Rate This
  • Comments 12

When we work with relational database and especially when with larger data we generally go for custom paging. This allows us to create superfast application.


The simple logic for paged query is like,


Let’s suppose you have 100 rows. Now you want to get data of page size 10 for page 2.


So the starting record would be


StartRecord = (PageNumber – 1) * PageSize


For page 2 it would be


StartRecord = (2 – 1) * 10 = 10 (may be you need to +1 to skip one record)


Now when this comes to LINQ to SQL scenario remains the same where the implementation is little different.


NorthWindDataContext db = new NorthWindDataContext();


var query = from c in db.Customers

            select c.CompanyName;


//Assuming Page Number = 2, Page Size = 10

int iPageNum = 2;

int iPageSize = 10;


var PagedData = query.Skip((iPageNum - 1) * iPageSize).Take(iPageSize);




Generated T-SQL,

For SQL Server 2000 the provider does not support Skip().


For SQL Server 2005


SELECT [t1].[CompanyName]
    SELECT ROW_NUMBER() OVER (ORDER BY [t0].[CompanyName]) AS [ROW_NUMBER], [t0]
    FROM [dbo].[Customers] AS [t0]
    ) AS [t1]
WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [10]
-- @p1: Input Int (Size = 0; Prec = 0; Scale = 0) [10]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30428.1




Leave a Comment
  • Please add 1 and 4 and type the answer here:
  • Post
  • PingBack from

  • wow! that looks so simple. I did CP based on Scott Mitchell's solution that combines datasource with stored procs. His ideas are good but I always feel there gotta be neater ways. Does this 'skip' thing perform as well as a stored proc? I hope it does. Also what about sorting while using CP? man, can't wait to try LINQ once it's finally released.

  • @ RUI

    Yes it does


  • At first glance this looks terrible ....

    Is this pulling all customers from the datastore or is there some clever extension method on the linq to sql parser that restricts by row_number?

    I'd like to see the sql that hits the database if possible.

  • Very good, that all was I need.

  • @RUSure

    Yes, there is a clever extension method that restricts by row number.  The SQL from the article shows it.

  • This is great, thanks for you post as its very useful.

  • Just echoing what @hobbit125 said in response to @RUSure.

    This is awesome - thank you!

  • Hi Everybody,

    it selects from the table. But i need while searching.

    i need the total records as well

  • Thanks, that saved me a lot of work!

  • hello,

    I from Iran,

    Thank you for above code

  • In SQL Server 2012+ you have the Offset Fetch Next statement. It would be interesting to see if LINQ to SQL in VS 2012+ uses this new construct behind the scenes.

Page 1 of 1 (12 items)