Cursor Class
Contains methods to fetch records and to get the number of cursor rows returned from a
SOQL query.
Namespace
Usage
A cursor is created when a SOQL query is executed on a Database.getCursor() or a Database.getCursorWithBinds() call. When the SOQL query is invoked, the corresponding rows are returned from the cursor. The maximum number of rows per cursor is 50 million, regardless of the operation being synchronous or asynchronous.
Example
1public with sharing class QueryChunkingQueueable implements Queueable {
2 private Database.Cursor locator;
3 private Integer position;
4
5 public QueryChunkingQueueable() {
6 locator = Database.getCursor(
7 'SELECT Id FROM Contact WHERE LastActivityDate = LAST_N_DAYS:400',
8 AccessLevel.USER_MODE);
9 position = 0;
10 }
11
12 public void execute(QueueableContext ctx) {
13 Integer remainingRows = locator.getNumRecords() - position;
14 if (remainingRows == 0) {
15 return; // Nothing to do
16 }
17
18 // Take the minimum of batch size and remaining rows to avoid over-fetching
19 Integer fetchSize = Math.min(200, remainingRows);
20
21 List<Contact> scope = locator.fetch(position, 200);
22 position += scope.size();
23 // do something, like archive or delete the scope list records
24 if (position < locator.getNumRecords()) {
25 // process the next chunk
26 System.enqueueJob(this);
27 }
28 }
29}Cursor Methods
The following are methods for Cursor.
fetch(position, count)
Fetches cursor rows that correspond to the offset position and the specified record
count. The maximum number of rows per cursor is 50 million, regardless of whether the operation
is synchronous or asynchronous. Calling the Cursor.fetch()
method counts against the SOQL query limit, and the rows fetched count against the SOQL query
row limit. You can make a maximum of 100 Cursor.fetch() calls
per transaction.
Signature
public static List<SObject> fetch(Integer position, Integer count)
Parameters
getNumRecords()
Gets the number of rows returned in an Apex cursor from a Cursor.fetch(position, count) operation.
Signature
public static Integer getNumRecords()
Return Value
Type: Integer