Sub topic 7
Filtering Rows with WHERE Before Grouping
This chapter assumes you know basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and have seen COUNT, SUM, and GROUP BY. Here you will learn what WHERE does in an aggregate query and when it runs.
The order of work
In an aggregate query, WHERE runs first. Salesforce picks the rows that match the filter. It then groups only those rows and calculates the aggregate functions on each group.
This means WHERE changes the numbers inside every group. It does not remove groups after they are built. That job belongs to HAVING, which a later chapter covers.
A worked example
Suppose you want the total of open opportunities for each account. Closed opportunities must not count toward the total.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountIdSalesforce does these steps:
- It reads Opportunity records and keeps those where
IsClosedis false. - It groups the remaining rows by
AccountId. - It adds up
Amountin each group.
An account with only closed opportunities has no rows left after step 1. It does not appear in the result at all. It does not appear with a total of zero.
WHERE can use fields you do not select
The WHERE clause may filter on any field you are allowed to query. It does not have to be in the SELECT list or the GROUP BY clause.
SELECT LeadSource, COUNT(Id) leadCount
FROM Lead
WHERE CreatedDate = THIS_YEAR AND IsConverted = false
GROUP BY LeadSourceThis counts only unconverted leads created this year. Neither CreatedDate nor IsConverted appears in the output.
What WHERE cannot do
WHERE filters individual records, so it cannot test an aggregate value. This query is invalid:
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE SUM(Amount) > 100000
GROUP BY AccountIdAt the WHERE stage no group exists, so there is no sum to compare. Salesforce rejects the query with an error. Use HAVING to filter on SUM(Amount).
Filtering early helps performance
Because WHERE runs before grouping, a selective filter reduces the number of rows Salesforce has to group. Filter on indexed fields where you can, such as CreatedDate or a lookup field. A narrow WHERE also helps you stay within governor limits. Aggregate queries still count the rows they scan, even though they return only a few result rows.
Using the same filter in Apex
A WHERE clause can use Apex variables with a colon prefix. This lets the same query serve different inputs.
Date startDate = Date.today().addMonths(-3);
for (AggregateResult ar : [
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
WHERE CloseDate >= :startDate AND IsClosed = false
GROUP BY StageName
]) {
System.debug(ar.get('StageName') + ': ' + ar.get('cnt') + ' opportunities, total ' + ar.get('total'));
}Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Putting an aggregate in WHERE | Query error | Move the condition to HAVING |
| Expecting empty groups to appear with 0 | Groups with no matching rows are missing | Handle missing keys in Apex, with a default of 0 |
| Filtering on the grouped value after grouping | Wrong totals when the filter should apply to rows | Put row-level filters in WHERE so they apply before the sums |
Exercise
You want the number of leads per LeadSource, counting only leads where Rating is 'Hot'. Write the query. Then explain why a LeadSource that has no hot leads does not appear in the result.
Show answer
SELECT LeadSource, COUNT(Id) leadCount FROM Lead WHERE Rating = 'Hot' GROUP BY LeadSource. WHERE runs before grouping, so leads that are not hot are removed first. A LeadSource with no hot leads has no rows left to form a group, so it produces no result row.