Sub topic 3
Summarizing values with SUM, AVG, MIN, and MAX
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT), Salesforce field types, and basic Apex syntax such as variables, loops, and casting.
What the four functions do
These functions collapse many rows into one value. The previous chapter covered counting. These four work on the values stored in a field.
| Function | Works on | Returns |
|---|---|---|
| `SUM(field)` | Number, currency, and percent fields | The total of all non-null values |
| `AVG(field)` | Number, currency, and percent fields | The mean of all non-null values |
| `MIN(field)` | Number, currency, date, date/time, and text fields | The lowest value |
| `MAX(field)` | Number, currency, date, date/time, and text fields | The highest value |
SUM and AVG need a numeric field. MIN and MAX also accept dates, which makes them useful for finding the earliest or latest record.
Using them without GROUP BY
Without GROUP BY, the query returns exactly one row that summarizes every record matching the WHERE clause.
SELECT SUM(Amount) total,
AVG(Amount) average,
MIN(Amount) smallest,
MAX(Amount) largest
FROM Opportunity
WHERE IsWon = trueIn Apex, a single-row aggregate query can be assigned to one AggregateResult. You read each value with get and cast it.
AggregateResult ar = [
SELECT SUM(Amount) total, MAX(CloseDate) latest
FROM Opportunity
WHERE IsWon = true
];
Decimal total = (Decimal) ar.get('total');
Date latest = (Date) ar.get('latest');
System.debug('Won total ' + total + ', last close date ' + latest);Nulls are ignored
All four functions skip null values. This matters most for AVG. Suppose three opportunities have amounts 100, 200, and an empty Amount. SUM returns 300 and AVG returns 150, because the average divides by 2, not 3. If no row has a value, each function returns null, so check for null before using the result in arithmetic.
Combining them with GROUP BY
Add GROUP BY and you get one summary row per distinct value of the grouped field.
SELECT StageName,
SUM(Amount) total,
AVG(Amount) average,
MIN(CloseDate) earliest,
MAX(CloseDate) latest
FROM Opportunity
GROUP BY StageNameEach row describes one stage. Every field in the SELECT list must be either an aggregate function or listed in GROUP BY. Here StageName is grouped, and the other four columns are aggregates, so the query is valid.
Common errors
- Selecting an ungrouped field. Adding
Nameto the query above fails, because a group has many names and the query cannot pick one. - Using SUM or AVG on a non-numeric field.
SUM(StageName)is rejected. UseMINorMAXif you need text ordering. - Omitting an alias. Without one, Apex sees the column as
expr0,expr1, and so on. These names depend on position, so a reorderedSELECTlist silently changes which value you read. - Wrong cast.
getreturnsObject. Cast to the type the field produces, such asDecimalfor currency sums orDatefor date results.
Exercise
An Opportunity query returns four rows for one account with Amount values 500, 1500, null, and 1000. What do SUM(Amount) and AVG(Amount) return, and why does AVG not return 750?
Show answer
SUM(Amount) returns 3000 and AVG(Amount) returns 1000. Aggregate functions ignore null values, so AVG divides 3000 by the 3 non-null amounts, not by all 4 rows. Dividing by 4 would give 750.
Exercise
Write a SOQL query that returns, for each AccountId, the most recent CloseDate among won opportunities, using the alias lastWon.
Show answer
SELECT AccountId, MAX(CloseDate) lastWon FROM Opportunity WHERE IsWon = true GROUP BY AccountId