SIMPLE PAGINATION VS CURSOR PAGINATION
Jan 19, 2024 Copy Link
Let's consider we have a bulk of users (E.g. 1000 users) and want to show them in the `index`
view. We will not show them all on ONLY one page because, it's hard for the user to scroll all these rows and also, hard for the database performance because the larger the table, the higher the query time
So, pagination is coming for that reason there are almost three types of pagination, and we will focus ONLY on Simple Pagination
and Cursor Pagination
PERSONALLY, I prefer the
Cursor Pagination
.
Simple Pagination
is built on the Offset
and Limit
in SQL
. The Offset
works by skipping N rows and Limit
works by getting the other N rows that catch them up. Let's assume that we will display 10 records per page so, to get the first 10 records on the first page we will skip no rows and retrieve 10 records, and then when we click the Next button, the database will trigger a query to skip the first 10 rows that have already been displayed in the first page and getting the second 10 records after that when we click the Next button again the database will skip the 20 rows and retrieve 10 records and so on...
Have you noticed anything?!
When we skipped the 20 rows we walked through the first 10 records that we had already walked through BEFORE because the database engine is not too smart enough to guess that it walked through these rows before. We are talking about 1000 records and It's straightforward what if we have a million records?
In the
Simple Pagination
the database engine visits the records that it has already gone through to see which record it must start with.
On the other hand, the database engine provides another nice way to paginate your records which is Cursor Paginating
, in this type, the database engine generates a random and not human-readable string but, it contains states
about the last record that has been presented to the user, so instead of fetching all records and then discarding the first N records, it fetches only the records after the last position
I will not talk about the other advantages and disadvantages of each type because they are not related to performance issues which is my goal in this Tip. Also, there is another type called
Offest & Limit with Deffred Joins
and I think it's not as well-known as the first two types.
Laravel supports these two types of paginating and you can dive into this Tip through Laravel documentation.