Home SalesforceApex Implementing Apex Cursors for Optimal Resource Management in Salesforce

Implementing Apex Cursors for Optimal Resource Management in Salesforce

by Dhanik Lal Sahni

Apex cursors allow us to divide the processing of a SOQL query result into batches that can be handled within the context of a single transaction. Cursors allow us to work with large query result sets without returning the entire set. We can traverse a query result in batches, with the option to move forward and back in the result set.

Apex Cursors is an alternative to batch Apex and addresses some limitations. Cursors are powerful because they can be used in a series of queued Apex jobs.

Use Case for this Feature Implementation

My Bank gets a lot of loan applications daily. This application needs to be verified properly before the loan is sanctioned. The system will email all customers to reply with the required documents within the provided timeline.

Solution

We will create a queueable apex class to email customers whose document verification is pending. This apex class will use a new Apex Cursor to divide and fetch records.

How does the Cursor work?

When a database executes a SOQL query using getCursor() or Database.getCursorWithBinds(), a cursor is created. When the Cursor.fetch(integer position, integer count) method is called with an offset position and a count of records to fetch, the cursor returns the corresponding rows. The maximum number of rows allowed per cursor is 50 million, regardless of whether the operation is synchronous or asynchronous. Cursor.getNumRecords() returns the number of cursor rows returned from the SOQL query.

Summary

Apex Cursor can be used in Queuable apex to handle high-volume and high-resource processing jobs. It is particularly useful in handling large data sets efficiently, as it fetches the data in batches rather than loading all records into memory at once, thereby conserving resources and improving performance.

References:

Use Cursors for Expanded SOQL Query Result Support (Beta)

Similar Posts

GraphQL Query Generator in Salesforce Apex

Object Initializer in Salesforce Apex

Avoid Batch Apex and Use Queueable Class

Optimize SOQL Filter in Apex Code

Apex Trigger Code Optimization

Optimize Apex Code by Metadata Caching

Optimizing Loop in Apex Code

Top Developer Features in Salesforce Spring ’24 Release


You may also like

Leave a Comment