I have a trigger on my child object .and when certain field of that child record is updated i need to recalculate totalfield, on my lookup parent

Now i am kind of hitting SOQl limit Issue is I can have 200 children passed in a single context.Which means 200 lookup parent In addition to 200lookup parents,sometime due to change in lookup,i need to update old parent records as well.which means 400parents.

Now each parent can have a maximum of 10,000 children(Since Trigger context variable need not have these children I am requiring db)

In my trigger on child this is how i do, I collect all parents that is affected in parentschanged set

list<AggregateResult> aggRes = [SELECT sum(total__c) ,parent__c FROM child__c where parent__c in :parentschanged GROUP BY parent__c limit :(Limits.getLimitQueryRows()-Limits.getQueryRows()) ];
            for(aggregateresult agg :aggres)
            triggerhandler.parentstoupdate.put((id)(agg.get('parent__c')),new parent__c(id=(id)(agg.get('parent__c')),total__c = (decimal)(agg.get('totalsum'))));      

if i do maths,In a single context i can 400parents and above query can return me 400*10000. (as i have put limit it wont,but i need to know is there a better way to handle this situation

One option i could think of is, Put logic inside code to see whether update/insert and then modify total__c field as it is. I add a custom formula to my child for total__c and then rest logic goes into code

is there any other neater way to do this?


There is a free App Exchange tool (Declarative Lookup Rollup Summaries Tool) available on below location, which handles "Rollup Summary" for lookup fields. Try below App Exchange product (Declarative Lookup Rollup Summaries Tool) :



One alternative is to use scheduler and batch apex.

1) Add new field on parent called is_processed__C (default false) 2) In child records trigger update is_processed__C = false
3) Write scheduler to invoke at every hour and start batch
4) In batch get all the children of all parents where is_processed__c == FALSE order by parent ID
5) calculate roll up for each parent and update roll up
6) Also update is_processed__C = true *** Very important
7) While processing check if you are approaching limit if yes then halt your processing and wait for next invocation of scheduler

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.