Hello Friends, In this post, we will understand about cursor-based pagination in apex. so, let's get started, when dealing with large datasets in Salesforce, efficient data retrieval is crucial. Standard offset-based pagination can be slow and inefficient, especially as the dataset grows. That's where cursor-based pagination comes in—a more scalable and performance-friendly approach. In this post, we’ll explore what cursor-based pagination is, why it matters, and how to implement it in Apex.

Cursor based pagination in apex

Cursor-based pagination, also known as keyset pagination, uses a unique value from the last record of the previous page (like an Id or timestamp) to fetch the next set of results. Unlike offset-based pagination, which skips a number of records (e.g., OFFSET 50), cursor-based pagination remembers the "last seen" record and continues from there.

Example:

 public class CursorBasedProcessor{
    private Id lastProcessedId;
    
    public void processRecords(){
        String query='SELECT Id,Name FROM Account';
        if(lastProcessedId!=null){
            query+=' WHERE Id>:lastProcessedId';
        }
        query +=' ORDER BY Id LIMIT 2000';
    }
    List<Account> records=Database.query(query);
    if(!records.isEmpty()){
        //write login to process your data
        
        //update cursor
        lastProcessedId=records[records.size()-1].Id;
        
        //continue processing if more records exist
        if(records.size()==2000){
            processRecords(); //recursive call
        }
    }
 }

Why Use Cursor-Based Pagination?

Here’s why cursor-based pagination is better, especially in large datasets:

1) Performance: Offset-based queries get slower with larger offsets. Cursor-based queries avoid scanning skipped rows.

2) Consistency: Cursor-based pagination avoids issues where the dataset changes (new records inserted/deleted) while paginating.

3) Scalability: Handles large volumes of data more efficiently, reducing CPU time and heap usage in Apex.

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.