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?

  • 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 Aug 25 '17 at 15:11
  • @Adrian, indeed, you are right! I just didn't notice that there are invoice items without a product. Thank you! – Eduard Aug 25 '17 at 15:21
4

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

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.