Query large sets of records in Salesforce using queryMore

Posted on 15-01-2013 09:42 by graham
While using Salesforce Metadata API, you often have to execute queries that will return large result sets. Salesforce puts a limit of 2000 on the call of the query() method. In order to fetch the entire result set, you need to call queryMore().

The code below shows how to do this in Java:
public static List<SObject> queryLargeSet (String query, PartnerConnection connection)
{
List<SObject> allObjects = new ArrayList<SObject>();
QueryResult result;

try
{
result = connection.query(query);
boolean allRecordsFetched = false;

while (!allRecordsFetched)
{
for (int i = 0; i < result.getRecords().length; i++)
{
allObjects.add(result.getRecords()[i]);
}

allRecordsFetched = result.isDone();
if (!allRecordsFetched)
{
result = connection.queryMore(result.getQueryLocator());
}
}
}
catch (ConnectionException e)
{
e.printStackTrace();
}

return allObjects;
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems