Sub topic 3
Summarizing values with SUM, AVG, MIN, and MAX
This chapter covers the four aggregate functions that summarize numeric, currency, and date values in SOQL. It assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), understand Salesforce objects and field types, and can read simple Apex with variables, loops, and casting. Counting with COUNT and COUNT_DISTINCT is covered in the previous chapter, and GROUP BY follows in the next one.
What the four functions do
An aggregate function reads many rows and returns one value. SOQL provides four for summarizing field values:
| Function | Returns | Works on |
|---|---|---|
| SUM(field) | The total of all non-null values | Numeric and currency fields |
| AVG(field) | The mean of all non-null values | Numeric and currency fields |
| MIN(field) | The smallest value | Numeric, currency, date, date/time, time, text, picklist, and similar sortable fields |
| MAX(field) | The largest value | The same field types as MIN |
SUM and AVG only make sense for numbers, so SOQL accepts them only on numeric and currency fields. MIN and MAX also work on dates, date/times, and many text-like fields. For text, the "smallest" value is the one that sorts first. For picklists, the sort order follows the order of the picklist values as defined in the org, not alphabetical order.
A first query
This query summarizes every opportunity in the org:
SELECT SUM(Amount) totalAmount,
AVG(Amount) avgAmount,
MIN(Amount) smallest,
MAX(Amount) largest
FROM OpportunityWithout a GROUP BY clause, the query collapses all matching rows into a single result row. The words after each function (totalAmount, avgAmount, and so on) are aliases. They give each result a name you can use in Apex. The aliases chapter covers them in detail. For now, treat them as required in practice.
You can mix functions on different fields, and you can use MIN and MAX on dates:
SELECT MIN(CloseDate) firstClose,
MAX(CloseDate) lastClose,
SUM(Amount) total
FROM Opportunity
WHERE IsWon = trueThis returns the earliest and latest close date among won opportunities, along with their combined amount.
Running an ungrouped aggregate in Apex
A query with aggregate functions returns AggregateResult objects instead of Opportunity records. Even with no GROUP BY, the result is a list that contains one AggregateResult. You read each value by calling get with the alias, then cast it to the right type.
AggregateResult ar = [
SELECT SUM(Amount) total,
AVG(Amount) average,
MIN(CloseDate) earliest,
MAX(CloseDate) latest
FROM Opportunity
WHERE IsWon = true
];
Decimal total = (Decimal) ar.get('total');
Decimal average = (Decimal) ar.get('average');
Date earliest = (Date) ar.get('earliest');
Date latest = (Date) ar.get('latest');
System.debug('Total: ' + total);
System.debug('Average: ' + average);
System.debug('Range: ' + earliest + ' to ' + latest);Assigning the query directly to a single AggregateResult works here because an ungrouped aggregate query always returns exactly one row. Once you add GROUP BY, the query can return zero or many rows, and you must assign it to a List<AggregateResult> or iterate over it.
Return types in Apex
The type you cast to depends on the field and the function.
| Expression | Apex type returned by get |
|---|---|
| SUM or AVG on a currency or decimal field | Decimal |
| SUM or AVG on a double field | Double |
| SUM on an integer field | Integer or Long, depending on the field |
| MIN or MAX on a number | The field's own type |
| MIN or MAX on a date | Date |
| MIN or MAX on a date/time | Datetime |
| MIN or MAX on text | String |
If you are unsure, call get and print the value with System.debug, or inspect it with String.valueOf(ar.get('alias')). A wrong cast throws a System.TypeException at run time, not at compile time, because get returns a generic Object.
How null values behave
All four functions ignore null values. This has consequences you should plan for.
AVG(Amount)divides by the number of records that have a non-null Amount, not by the total record count. If half your opportunities have no Amount, the average reflects only the other half.SUM(Amount)skips nulls and does not treat them as zero. That gives the same total, but you cannot infer the record count from it.- If every value in the matching set is null, or no rows match at all, SUM, AVG, MIN, and MAX return null. They do not return 0.
The last point is a common source of NullPointerException errors. Consider this code:
AggregateResult ar = [
SELECT SUM(Amount) total
FROM Opportunity
WHERE StageName = 'Imaginary Stage'
];
Decimal total = (Decimal) ar.get('total');
// total is null here, so total + 100 would throw an exception
Decimal safeTotal = (total == null) ? 0 : total;
System.debug(safeTotal);Always check for null before doing arithmetic on an aggregate result when the filter could match nothing.
To see how many values contributed to an average, put COUNT on the same field next to it. COUNT(Amount) counts only non-null values, so it matches the divisor AVG uses.
SELECT AVG(Amount) avgAmount,
COUNT(Amount) withAmount,
COUNT(Id) allRecords
FROM OpportunityIf withAmount is much smaller than allRecords, the average describes only part of your data.
Currency, rounding, and multi-currency orgs
In an org with multiple currencies enabled, each record stores its amount in its own currency. A plain SUM(Amount) adds the raw numbers from those records without converting them. The result is mixed and rarely meaningful. To get a total in the corporate currency, use the convertCurrency() function inside the aggregate:
SELECT SUM(convertCurrency(Amount)) totalCorporate
FROM Opportunity
WHERE IsWon = trueUse convertCurrency() only when the org has multiple currencies. In a single-currency org the function is not needed.
AVG on a currency field can return a value with more decimal places than the field shows in the interface. Round it in Apex when you display it:
Decimal avg = (Decimal) ar.get('average');
Decimal rounded = avg == null ? null : avg.setScale(2);Combining the functions with WHERE
A WHERE clause filters rows before the functions run. The aggregates only see the rows that survive the filter.
SELECT SUM(Amount) openTotal,
AVG(Amount) openAverage,
MAX(Amount) biggestOpenDeal
FROM Opportunity
WHERE IsClosed = false
AND CloseDate = THIS_QUARTERThis summarizes only open opportunities closing in the current quarter. You cannot put an aggregate function in WHERE. A query such as WHERE SUM(Amount) > 1000 is invalid. Filtering on an aggregate value needs a HAVING clause, which a later chapter covers.
Rules for mixing fields and functions
Once a query contains an aggregate function, every other field in the SELECT list must either also be wrapped in an aggregate function or appear in a GROUP BY clause. This query fails:
SELECT StageName, SUM(Amount) total
FROM OpportunityIt fails because StageName is neither aggregated nor grouped, so SOQL has no single value to return for it. The fix is to group by that field, which the next chapter covers:
SELECT StageName, SUM(Amount) total
FROM Opportunity
GROUP BY StageNameA few other restrictions apply:
- Aggregate queries cannot use
FOR UPDATE. - Aggregate queries cannot use
OFFSETin some contexts, so check the current SOQL reference before relying on it. - You cannot apply SUM or AVG to a text or date field. MIN and MAX accept those types.
- Some field types, such as long text areas and certain compound fields, cannot be aggregated at all.
Governor limits to keep in mind
Aggregate queries count against the same limits as other SOQL queries. Each query counts toward the limit on SOQL queries per transaction. In addition, each row an aggregate query processes counts toward the limit on rows retrieved. In synchronous Apex, this limit is 50,000 rows per transaction. An aggregate query can scan more than that, but historically a query that touches a very large number of records in a single transaction can fail with a "Too many query rows" or a non-selective query error. When you run these queries on large data volumes, filter with an indexed field in the WHERE clause so the query stays selective.
Because an ungrouped aggregate returns one row, it is far cheaper in heap and CPU than loading all records and adding them in a loop. Compare these two approaches:
// Wasteful: loads every record, then adds in Apex
Decimal total = 0;
for (Opportunity o : [SELECT Amount FROM Opportunity WHERE IsWon = true]) {
if (o.Amount != null) {
total += o.Amount;
}
}
// Better: the database does the work
AggregateResult ar = [SELECT SUM(Amount) total FROM Opportunity WHERE IsWon = true];
Decimal total2 = (Decimal) ar.get('total');The second version returns one row and uses far less heap.
Choosing the right function
The diagram shows how to pick a function for a given question.
Common mistakes
- Assuming zero for empty results. Aggregates return null when nothing matches. Check for null before arithmetic.
- Reading the average as a company-wide figure. AVG skips null values, so compare it with
COUNT(Id). - Using a wrong cast.
getreturnsObject. Casting a Decimal to Integer throws an exception. - Summing mixed currencies. Use
convertCurrency()in multi-currency orgs. - Putting an aggregate in WHERE. Use HAVING for conditions on aggregate values.
- Omitting aliases. Without an alias, the result gets a generated name such as
expr0, which is easy to mix up when a query has several aggregates.
Exercise
An org has 10 opportunities closing this quarter. Four have a null Amount, and the other six have amounts of 100, 200, 300, 400, 500, and 600. What do SUM(Amount) and AVG(Amount) return, and what would AVG return if you wrongly assumed nulls count as zero?
Show answer
SUM(Amount) returns 2100, because nulls are skipped. AVG(Amount) returns 350, which is 2100 divided by the 6 non-null values. If nulls counted as zero, the average would be 2100 divided by 10, which is 210. SOQL does not do this, so use COUNT(Amount) next to AVG to see how many values it used.
Exercise
Write a SOQL query that returns the earliest and latest CloseDate and the total Amount for opportunities that are not closed. Then write the Apex line that reads the total safely, so that an empty result gives 0 instead of null.
Show answer
The query is SELECT MIN(CloseDate) earliest, MAX(CloseDate) latest, SUM(Amount) total FROM Opportunity WHERE IsClosed = false. In Apex, after assigning the query to AggregateResult ar, use Decimal total = (Decimal) ar.get('total'); Decimal safeTotal = (total == null) ? 0 : total;.