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
}
}
}
0 Comments
Post a Comment