I have 2 objects, parent and child. They have a master detail relationship. Child has a field called Expenses__c and parent has a field called My_Total_Expenses__c.

I want to show the total sum of Expenses__c field in the parent My_Total_Expenses__c field. In the parent object there is also a rollup summary field in which summarised object is child and field to aggregate is Expenses__c.

I have written this code but it is throwing while inserting the data. I am calling this code in a trigger.

public class PapaBachaController {
    public static void oninsert(List<Child__c> ch){
        set<double> bc= new set<double>();
        for(Child__c c:ch){
            if(c.Expenses__c !=null){
        List<Parent__c> ul=new List<Parent__c>();
        List<aggregateresult> ar=[select sum(Expenses__c) from Child__c];

            for(aggregateresult results:ar){

            Parent__c a=new Parent__c();
            update ul;

  • 2
    You already have master detail relastionship, and you are already using roll up summary field on parent, why you need to write code for aggregation of expenses? – Radhe Radhe Mar 14 '19 at 9:09

You should place an alias just after the aggregation like:

ar=[select sum(Expenses__c)myAliasName from Child__c]

Then you could access the aggregation result using:


If you are not using aliasing, then a default name is being assigned. It starts as expr0 and continues till exprN. In your case is the following:


More info in: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm

  • a.My_total_expenses__c=(double)results.get('expr0') could anyone define the line that what it is doing? – Sam-dev-sfdc Mar 14 '19 at 9:46
  • @user10253353, you have to either use alias names or auto-generated (indexed by position) names to access the "fields" retrieved in an aggregate result. This line gets the first (unaliased) "field" from the aggregate result. Note, however, I believe Radhe Radhe's comment on the question is right and you should be using a rollup. – Phil W Mar 14 '19 at 16:31
  • i am trying to do it manually through trigger and i have completed that – Sam-dev-sfdc Mar 14 '19 at 16:32

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.