Sub topic 1
What aggregate queries do and when to use them
A standard SOQL query returns records. An aggregate query returns summaries computed from those records: how many exist, what they add up to, or what the largest value is. This chapter explains what aggregate queries are, how their results differ from ordinary query results, and how to decide when to use one. Later chapters cover each function and clause in detail.
Prerequisites
This chapter assumes you already know:
- Basic SOQL syntax:
SELECT,FROM,WHERE,ORDER BY, andLIMIT. - Salesforce objects, fields, and field types such as Number, Currency, Date, and Picklist.
- Basic Apex: variables,
forloops, and casting a value to a type.
You do not need to know GROUP BY yet. This chapter introduces it only as far as the overview requires.
The problem aggregate queries solve
Suppose you need the total value of all open opportunities. One approach is to query every opportunity and add the amounts in Apex:
Decimal total = 0;
for (Opportunity o : [SELECT Amount FROM Opportunity WHERE IsClosed = false]) {
if (o.Amount != null) {
total += o.Amount;
}
}
System.debug('Open pipeline: ' + total);This works, but it has costs:
- Every matching record is transferred to Apex and counted against your query row limit.
- The loop uses CPU time and heap memory.
- If the data grows past the limits, the code fails at runtime.
An aggregate query asks the database to do the arithmetic and send back only the answer:
AggregateResult ar = [
SELECT SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
];
System.debug('Open pipeline: ' + ar.get('total'));The query returns one row instead of thousands. Moving the computation to the database is the main reason to use aggregate queries.
What counts as an aggregate query
A SOQL query is an aggregate query when its SELECT list contains an aggregate function. These are the functions this tutorial covers:
| Function | What it returns | Typical use |
|---|---|---|
| `COUNT()` | Number of rows that match | Quick record counts |
| `COUNT(field)` | Number of rows where the field is not null | Counting populated values |
| `COUNT_DISTINCT(field)` | Number of different non-null values | How many industries, owners, or sources exist |
| `SUM(field)` | Total of a numeric field | Revenue, quantities |
| `AVG(field)` | Mean of a numeric field | Average deal size |
| `MIN(field)` | Smallest value | Earliest date, lowest amount |
| `MAX(field)` | Largest value | Latest date, highest amount |
The GROUP BY clause splits the matching rows into buckets and applies the functions to each bucket separately. Without GROUP BY, the whole set of matching rows is one bucket, so the query returns a single row.
Two points about the functions are easy to miss:
- Except for
COUNT(), every aggregate function ignores null values.AVG(Amount)divides by the number of opportunities that have an amount, not by the number of opportunities. COUNT()with empty parentheses is different fromCOUNT(Id). The first has a special return shape, described next.
Two kinds of result
Apex handles aggregate results differently depending on the query.
A query that uses only COUNT() returns an Integer when you assign it to an Integer variable:
Integer openCount = [SELECT COUNT() FROM Opportunity WHERE IsClosed = false];
System.debug('Open opportunities: ' + openCount);Every other aggregate query returns a List<AggregateResult>. If the query has no GROUP BY, the list contains one element. AggregateResult is a generic result type. It is not tied to an object like Opportunity, because each row is a computed summary and not a stored record. You read values with get() and cast them to the type you expect.
AggregateResult ar = [
SELECT COUNT(Id) cnt, MIN(CloseDate) firstClose, MAX(CloseDate) lastClose
FROM Opportunity
WHERE IsWon = true
];
Integer cnt = (Integer) ar.get('cnt');
Date firstClose = (Date) ar.get('firstClose');
Date lastClose = (Date) ar.get('lastClose');
System.debug(cnt + ' won deals between ' + firstClose + ' and ' + lastClose);Words such as cnt and firstClose after each function are aliases. They name the column so that you can read it by name. Without an alias, Salesforce names the columns expr0, expr1, and so on, in the order they appear. That makes code fragile when someone later reorders the SELECT list. Aliases and AggregateResult get their own chapters.
If a query with no GROUP BY and an aggregate function matches no rows, you still get one row. For example, COUNT(Id) returns 0, and SUM and MAX return null. Check for null before you use these values in arithmetic.
From one total to a summary table
A single total answers one question. GROUP BY lets one query answer the same question for every category:
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceThis returns one row per distinct LeadSource value, with the number of leads for each. Leads with a null LeadSource form their own group, and its LeadSource value is null.
The next diagram shows how the pieces of an aggregate query fit together. Salesforce filters rows first, groups them, calculates the functions, and then filters the groups. The clause that does the last step, HAVING, comes in a later chapter.
If you leave out GROUP BY, steps C and E collapse. All rows form one bucket and the query returns one row.
When to use an aggregate query
Use one when the answer you need is a number or a short table of numbers, not a list of records. These are the common cases:
- Counts and totals for a page or dashboard component. Examples are open cases per queue and revenue per product family.
- Checks before an action. Examples are "does this account already have more than five open cases?" and "what is the latest
CloseDatefor this account?". - Roll-up values. Salesforce has roll-up summary fields only on master-detail relationships. For a lookup relationship, an aggregate query run in a trigger or in Apex is the usual way to compute the same total.
- Data-quality checks.
COUNT_DISTINCTandGROUP BYon a field can reveal unexpected values or duplicates. - Reducing limit consumption. A summary query avoids pulling thousands of records into Apex only to add them up.
When not to use one
Aggregate queries are not always the right tool:
- You need the records themselves. If you will update, display, or relate individual records, use a normal query. An
AggregateResulthas noIdof the source record, and you cannot pass it to DML. - A report or dashboard already does the job. If the summary is for people to read and you do not need it in code, a standard report is easier to maintain.
- You need fields that are not part of the summary. In an aggregate query with
GROUP BY, every non-aggregate field in theSELECTlist must also appear in theGROUP BYclause. You cannot select a record name next to a total. If you need the details, run a second query or use a different approach. - You need very large summaries with strict performance requirements. Aggregate queries still scan the matching rows, and they count toward governor limits. They are not free on large data volumes. The limits chapter covers this.
A worked comparison
Here is a task: show the number of leads for each lead source.
The record-based approach queries all leads and counts them in a map:
Map<String, Integer> counts = new Map<String, Integer>();
for (Lead l : [SELECT LeadSource FROM Lead]) {
Integer current = counts.containsKey(l.LeadSource) ? counts.get(l.LeadSource) : 0;
counts.put(l.LeadSource, current + 1);
}
System.debug(counts);The aggregate approach asks the database for the counts:
Map<String, Integer> counts = new Map<String, Integer>();
for (AggregateResult ar : [
SELECT LeadSource, COUNT(Id) cnt
FROM Lead
GROUP BY LeadSource
]) {
counts.put((String) ar.get('LeadSource'), (Integer) ar.get('cnt'));
}
System.debug(counts);Both produce the same map. The second version returns at most one row per lead source, which is a handful of rows regardless of how many leads exist. It is also shorter and easier to read.
Common first mistakes
- Selecting a field that is not grouped.
SELECT Name, COUNT(Id) FROM Accountfails becauseNameis neither aggregated nor in aGROUP BYclause. - Treating the result as a list of records. Assigning a grouped query to
List<Account>causes a compile error. UseList<AggregateResult>. - Forgetting the cast.
ar.get('cnt')returnsObject. Cast it toInteger,Decimal,Date, orStringbefore you use it. - Relying on default names. Reading
expr0works, but it breaks silently if theSELECTlist changes. Use aliases.
Exercise
A trigger needs to know the total Amount of all open opportunities for one account, stored in the variable accountId. A teammate proposes querying all open opportunities and summing the amounts in a loop. Write an aggregate query that returns the total instead, and explain why it is better. Also say what the query returns if the account has no open opportunities.
Show answer
AggregateResult ar = [SELECT SUM(Amount) total FROM Opportunity WHERE AccountId = :accountId AND IsClosed = false]; Decimal total = (Decimal) ar.get('total'); The query returns one row, so no opportunity records are loaded into Apex, which saves query rows, CPU time, and heap. If there are no matching opportunities, the query still returns one row, but total is null, so check for null (for example total = total == null ? 0 : total) before doing arithmetic.