1

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?

2
  • 3
    Clearly it did return a result. Why do you think it didn't? You seem to have invoice items with a null product.
    – Adrian Larson
    Commented Aug 25, 2017 at 15:11
  • @Adrian, indeed, you are right! I just didn't notice that there are invoice items without a product. Thank you!
    – Eduard
    Commented Aug 25, 2017 at 15:21

1 Answer 1

4

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

You must log in to answer this question.

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