Loading

How to Aggregate (SUM) Values Using SOQL in Apex

Udgivelsesdato: Jan 28, 2026
Beskrivelse

When trying to sum a currency field using a SOQL aggregate query inside an Apex trigger or class, you may see the following error:

`Save error: Illegal assignment from LIST<AggregateResult> to Decimal CalculateCharge.trigger`

Example code that triggers this error:

`TotalCharges__c = [SELECT sum(EntryCharge__c) FROM AllocationTable__c WHERE id=:id];`

Where TotalCharges__c is a currency field and EntryCharge__c is a currency expression field.

Løsning

This resolution explains how to correctly assign the result of a SOQL aggregate query (like SUM) to a Decimal variable in Apex.

Using AggregateResult in Apex

A SOQL aggregate query like `sum()` doesn't return the aggregated value directly as a Decimal — it returns a list of AggregateResult objects. To use the summed value, first capture the query result as an AggregateResult, then convert it to a Decimal using the `valueof` method, since the aggregation result can't be stored directly in a Decimal variable.

Example Code

`AggregateResult ar = [SELECT sum(EntryCharge__c) s FROM AllocationTable__c WHERE id=:id];
TotalCharges__c = decimal.Valueof(string.valueof(ar.get('s')));
system.debug('data = '+String.valueof(j.TotalCharges__c));`

What Each Line Does

  • The first line runs the SOQL SUM query and stores the result in an AggregateResult variable named `ar`, aliasing the summed value as `s`.
  • The second line pulls the aliased value out of the AggregateResult with `ar.get('s')`, converts it to a String, then converts that String to a Decimal — this two-step conversion is required because AggregateResult values can't be cast to Decimal directly.
  • The third line is optional and simply logs the resulting value for debugging.
Vidensartikelnummer

000385401

 
Indlæser
Salesforce Help | Article