Search code examples
databaseweb-applicationspagination

How does paging on a web page work?


What are the principles or implementation involved in making a result set from a database "pageable" ?

How is it possible to page over a million records without storing it in memory? What allows "jumping" from 5 to the 50th page number when there are 100 pages ?

I'm looking for a pseudo-code kind of explanation on how the paging is accomplished.


Solution

  • Basic premise is to remember the following:

    1. Define your page size i.e the number of records per page (PAGE_SIZE)
    2. Know the total number of records in the set. Then you can calculate how many pages there are. var numPages = totalNumRecords / PAGE_SIZE;
    3. Use a variable to track the page number i.e Page = 1
    4. Perform a simple Skip/Take algorithm shown below and you have the elements needed to page

    Skip((page - 1)*PAGE_SIZE).Take(PAGE_SIZE);

    So what will happen is when you hit the data source for results, you will skip to the set of records you want and take the prescribed amount. Hopefully this makes sense.