I just found a construct similar to the following in a colleague's code, which I didn't expect to even compile:
for (List<Lead> leads : [
SELECT Id FROM Lead LIMIT 1000
])
{
for (Lead lead : leads) {
// do some stuff
}
}
You can paste the code above into an Execute Anonymous window and it will execute without error.
What's going on here? As far as I know, [SELECT Id FROM Lead LIMIT 1000]
should return a List<Lead>
, but above we're looping over it as if it returned a List<List<Lead>>
.
The only documentation I can find about the [SELECT ...]
syntax being able to return anything other than a list of sObjects is at https://developer.salesforce.com/trailhead/apex_database/apex_database_soql, where it's noted that including LIMIT 1
in the query will cause it to return a single sObject instead of a List:
Account oneAccountOnly = [SELECT Name,Phone FROM Account LIMIT 1];
but that doesn't explain how my colleague's code can work.
Is the fact that this construct works a bug, or intentional behaviour? If it's intentional, is it documented anywhere, what's it for, and how does Apex decide how to split the results of the SOQL query into the multiple sub-Lists that my colleague is looping over?