Tuesday, June 18, 2013

Salesforce "invalid query locator" error

Symptom


Inline apex soql query returns "QueryException: invalid query locator" error. However executing the soql directly does not present this error.

A Possible Cause


Apex appears to have a limit on the number of child records that can be returned from a soql query. At time of writing this limit is 999 records. AFAIK this limit is undocumented.

Solution


Separate any subqueries out into one or more separate queries.

Example


The following apex returns one myParent record and all associated child records for the myChild1, myChild2 & myChild3 objects.

myParent__c p=[select id, (select id from myChild1__r), (select id from myChild2__r), (select id from myChild3__r) from myParent__c limit 1];

If the total number of child records >= 1000 then you will get the "invalid query locator" error.

Let's say myChild3__c has a large number of records. Then the solution would be as follows:

myParent__c p=[select id, (select id from myChild1__r), (select id from myChild2__r) from myParent__c limit 1];


myChild3__c[] c3s=[select id from myChild3__c where myParent__c=:myParent__c.Id];

No comments: