I am using a QueryLocator in my code. In one part of the code I call the .iterator() method to verify that it is not empty. Now I am going through writing a unit test and finding that I am unable to call .iterator() on the same QueryLocator twice. Is this by design or am I doing something wrong? Here is some anonymous apex to explain what I mean:

Database.QueryLocator queryLocator = Database.getQueryLocator([SELECT Id FROM Contact LIMIT 10]);

Database.QueryLocatorIterator it1 = queryLocator.iterator();


Database.QueryLocatorIterator it2 = queryLocator.iterator();


When I execute this (and I have Contacts in my DB), then the first debug will say true and then the next one says false.

1 Answer 1


The documentation has the following to say about iterator:

To iterate over a query locator, save the iterator instance that this method returns in a variable and then use this variable to iterate over the collection. Calling iterator every time you want to perform an iteration can result in incorrect behavior because each call returns a new iterator instance.

What that seems to mean is that you can only call iterator() once per QueryLocator. Since you are just interested in whether hasNext is true, just save the iterator and call hasNext twice (or save the result in a boolean). If you need to iterate over the collection twice, you may need to save each record in a List for later use.

  • Thanks although I prefer not to save this iterator solely for testing purposes. I would not mind if Salesforce would do what it says and give me a new iterator instance rather than just an empty iterator. Feb 18, 2016 at 21:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .