Sub topic 1
What Aggregate Queries Do and When to Use Them
Prerequisites
This chapter assumes you already know:
- Basic SOQL syntax:
SELECT,FROM,WHERE,ORDER BY, andLIMIT. - Salesforce objects, fields, and field types (text, number, currency, date).
- Basic Apex: variables, loops, and casting.
The working model
A regular SOQL query returns one row for each record that matches. An aggregate query returns summary rows. Instead of listing every lead, you ask how many leads exist, or how many there are for each lead source.
Salesforce computes the summary on the server. Your code receives only the result rows, not the underlying records.
Aggregate queries use two kinds of syntax:
- Aggregate functions such as
COUNT(Id)orSUM(Amount), which reduce many values to one. - The
GROUP BYclause, which splits the matching records into groups and computes the function once per group.
Without GROUP BY, the whole result set is one group. The query below returns a single row.
SELECT COUNT(Id) total
FROM LeadWith GROUP BY, you get one row per distinct value of the grouped field.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
GROUP BY LeadSourceEach row holds a LeadSource value and the number of leads with that value. Leads with an empty LeadSource form their own group, and its LeadSource value is null.
The aggregate functions
The tutorial covers these functions in later chapters. For now, here is what each one does.
| Function | Result |
|---|---|
| `COUNT(Id)` | Number of records |
| `COUNT_DISTINCT(field)` | Number of distinct non-null values |
| `SUM(field)` | Total of a numeric field |
| `AVG(field)` | Average of a numeric field |
| `MIN(field)` and `MAX(field)` | Lowest and highest value |
Here is a distinct count in action. It returns how many different industries appear on accounts.
SELECT COUNT_DISTINCT(Industry) industryCount
FROM AccountWhen to use an aggregate query
Use one when you need a summary and not the records themselves. Typical cases are:
- Totals and counts for a dashboard, a report-like page, or an integration.
- Checks such as "how many open opportunities does each account have?"
- Data profiling, for example how many distinct values a field holds.
Prefer an aggregate query to loading records and summing them in Apex. A query that returns 50 summary rows is far cheaper than one that returns 50,000 records. It uses less heap memory and less CPU time, and it avoids the per-query row limit for the records themselves.
Do not use an aggregate query when you need the individual records, for example to update them. Aggregate results do not carry record Id values (unless you group by Id), so you cannot update records from them.
What to watch for
In Apex, an aggregate query returns AggregateResult objects, not typed records such as Lead. You read each value with get() and cast it. Chapters later in this tutorial cover this in detail.
Exercise
A teammate loads all Opportunity records into a list and loops over them in Apex to add up the Amount field for each StageName. Which SOQL query would replace this loop, and why is it better?
Show answer
Use SELECT StageName, SUM(Amount) total FROM Opportunity GROUP BY StageName. Salesforce does the grouping and summing on the server and returns one row per stage. This avoids transferring every record into Apex, which saves heap memory and CPU time and stays clear of the row limit.
Exercise
What does SELECT COUNT(Id) total FROM Lead return when there is no GROUP BY clause?
Show answer
A single row containing the number of matching leads, because the entire result set is treated as one group.