[SalesForce] Modify the results of an aggregate result directly

I need to add a variable to an Aggregate Result list.

In the semi pseudocode below I attempt to assign a value to the AggregateResult[] if the sum is 0.

This does not work. The aggRes is later used in a function and I do not want to have to put the results of the aggregate result into a map for a solution.

Is it possible to accomplish what I'm doing and directly modify the AggregateResult?

AggregateResult[] aggRes = [Select Expense__c, Sum(Cost__c) from CustomObject__c Group By Expense__c]; 

for(AggregateResult ar: aggRes) {
    if(ar.get(Cost__c) == 0) {
        ar.put(Cost__c, 10);
    }
}

Best Answer

No. If you attempt to modify the AggregateResult, you'll get a runtime error. Here's an example from my dev org:

AggregateResult[] ar = [select name name from account group by name];
System.debug(ar[0]);
ar[0].put('name','Test2');
System.debug(ar[0]);

Result:

EXECUTION_STARTED

CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex

LIMIT_USAGE|[1]|SOQL|1|100

LIMIT_USAGE|[1]|AGGS|0|300

LIMIT_USAGE|[1]|SOQL_ROWS|69|50000

ENTERING_MANAGED_PKG|

USER_DEBUG|[2]|DEBUG|AggregateResult:{name=,}

ENTERING_MANAGED_PKG|

EXCEPTION_THROWN|[3]|System.SObjectException: Invalid field name for AggregateResult

FATAL_ERROR|System.SObjectException: Invalid field name for AggregateResult

The documentation also states that the object is read-only, so it is not possible to modify the values within the result object.

AggregateResult is an sObject, but unlike other sObject objects such as Contact, it is read-only and it is only used for query results.

Related Topic