[SalesForce] AggregateResult looping over empty query

I noticed weird behavior with for-loops when used with AggregateResult SOQL. Consider the following code (executed in the After Delete trigger context on the Order_Invoice_Item__c custom object):

trigger Test_Trigger on Order_Invoice_Item__c (before insert, before update, after insert, after update, after delete, after undelete)
{
    set<Id> prdIds = new set<Id>();

[90]:    System.debug('>>> prdIds: ' + prdIds);
for(AggregateResult ag : [SELECT Sum(Amount__c) amt, Sum(Quantity__c) qty, Product__c
                          FROM Order_Invoice_Item__c 
                          WHERE Product__c In : prdIds
                          Group By Product__c])
{

    Product2 prd = new Product2();
    prd.Id = (Id) ag.get('Product__c');
    prd.Average_Cost_Cal__c = (double) ag.get('amt')/(double) ag.get('qty');                                  
    prdList.add(prd);
[101]: System.debug('>>> ag: ' + ag);
}
[103]: System.debug('>>> prdList: ' + prdList);
}

The thing is prdIds is empty. But when the code is running this for-loop is executed one time, despite the fact that the SOQL query doesn't return any records.

Debug info:

enter image description here

Is it a side effect of for-loops when used with AggregateResult? Or am I missing something?

Best Answer

Your query clearly did return results. You have Order_Invoice_Item__c records whose Product__c is equal to null.

Related Topic