Sub topic 7
Filtering rows with WHERE before grouping
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and know how COUNT, SUM, and GROUP BY work from the earlier chapters. It also assumes you can read simple Apex with loops and casting.
Where WHERE runs in an aggregate query
In an aggregate query, WHERE decides which records are eligible to be grouped. The database applies it first. It then groups the surviving rows and computes the aggregate functions over each group.
The processing order in SOQL is:
- FROM and WHERE select the records.
- GROUP BY puts those records into groups.
- The aggregate functions (COUNT, SUM, AVG, MIN, MAX) are computed per group.
- HAVING removes groups.
- ORDER BY and LIMIT shape the final rows.
Because WHERE runs before any aggregate exists, it can only test values of individual records. It cannot test a total or a count.
A first filtered aggregate
This query counts open opportunities per stage. Closed opportunities never enter a group.
SELECT StageName, COUNT(Id) cnt
FROM Opportunity
WHERE IsClosed = false
GROUP BY StageNameWithout the WHERE clause, you would get one row for every stage, including Closed Won and Closed Lost, and the counts would include every record. With it, the closed stages disappear from the result, because no record in them survived the filter.
The WHERE field does not have to be selected or grouped
The rule that every non-aggregated selected field must appear in GROUP BY applies only to the SELECT list. A WHERE clause can test any filterable field on the object, whether or not it appears in SELECT or GROUP BY. In the query above, IsClosed is in neither list, and that is fine.
What you can use in WHERE
Everything you already use in ordinary SOQL works here.
| Filter type | Example |
|---|---|
| Comparison | `WHERE Amount > 5000` |
| Set membership | `WHERE StageName IN ('Prospecting', 'Qualification')` |
| Pattern | `WHERE Name LIKE 'Acme%'` |
| Null test | `WHERE LeadSource != null` |
| Date literal | `WHERE CloseDate = THIS_YEAR` |
| Relationship field | `WHERE Account.Industry = 'Energy'` |
| Combined logic | `WHERE IsClosed = false AND Amount > 1000` |
You can also use a semi-join, which filters by a subquery on another object:
SELECT StageName, SUM(Amount) total
FROM Opportunity
WHERE AccountId IN (SELECT AccountId FROM Case WHERE IsClosed = false)
GROUP BY StageNameThis totals opportunity amounts per stage, but only for accounts that currently have an open case.
Combining several conditions
Use parentheses when you mix AND and OR. SOQL requires them when you mix the two operators in one clause, so the query never relies on an implicit order.
SELECT LeadSource, COUNT(Id) cnt
FROM Lead
WHERE IsConverted = false
AND (Rating = 'Hot' OR Rating = 'Warm')
GROUP BY LeadSourceAggregates are not allowed in WHERE
The most common error in this area is trying to filter on an aggregate in WHERE.
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE SUM(Amount) > 100000
GROUP BY AccountIdThis query is rejected. When WHERE runs, no sums exist yet. To filter on a total, move that condition to HAVING, which the next chapter covers in detail:
SELECT AccountId, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000Here both clauses appear together. WHERE narrows the records to open opportunities. HAVING then keeps only the accounts whose open total exceeds 100000.
| Question | WHERE | HAVING |
|---|---|---|
| What does it test? | One record's field values | A group's aggregate value |
| When does it run? | Before grouping | After grouping |
| Can it use SUM, COUNT, and so on? | No | Yes |
| Can it test a field that is not selected? | Yes | Only through aggregate expressions or grouped fields |
| Effect on aggregates | Changes what gets counted and summed | Leaves the aggregates unchanged and removes whole rows |
The last row of the table matters for interpreting results. A WHERE filter changes the numbers inside the groups. A HAVING filter never does.
How WHERE changes the numbers
Suppose an account has three opportunities: one open for 40000, one open for 70000, and one closed for 500000.
| Query | Group for this account | Result |
|---|---|---|
| No WHERE | All three records | total = 610000 |
| `WHERE IsClosed = false` | Two open records | total = 110000 |
| `WHERE IsClosed = false` with `HAVING SUM(Amount) > 100000` | Two open records, then the group is tested | total = 110000 (row kept) |
| `HAVING SUM(Amount) > 100000` only | All three records, then the group is tested | total = 610000 (row kept) |
The last two rows keep the same account but report different totals. If you wanted the open total and put the condition only in HAVING, your number would be wrong without any error to warn you.
Null values and filtering
Aggregate functions skip null values, and GROUP BY treats null as its own group. WHERE is how you control both effects.
COUNT(Id)counts every record, because Id is never null.COUNT(LeadSource)counts only records where LeadSource has a value.SUM(Amount)andAVG(Amount)ignore records with a null Amount.AVGdivides by the number of non-null values, not by the number of records.- If a grouped field is null on some records, you get a group whose key is null. In Apex,
ar.get('LeadSource')returns null for that row.
To drop the null group, filter it out before grouping:
SELECT LeadSource, COUNT(Id) cnt
FROM Lead
WHERE LeadSource != null
GROUP BY LeadSourceIf you want the null group, leave the filter out and handle the null in your Apex code.
Passing filter values from Apex
In Apex, use bind variables in WHERE instead of building the query string by hand. Bind variables are safe against SOQL injection and let you pass in collections.
Set<String> stages = new Set<String>{ 'Prospecting', 'Qualification', 'Proposal/Price Quote' };
Decimal minAmount = 1000;
for (AggregateResult ar : [
SELECT StageName, COUNT(Id) cnt, SUM(Amount) total
FROM Opportunity
WHERE IsClosed = false
AND StageName IN :stages
AND Amount >= :minAmount
GROUP BY StageName
]) {
String stage = (String) ar.get('StageName');
Integer cnt = (Integer) ar.get('cnt');
Decimal total = (Decimal) ar.get('total');
System.debug(stage + ': ' + cnt + ' opportunities, total ' + total);
}The filter is applied on the database side. Your loop only sees one row per stage that has matching records. If no records match, the loop runs zero times and there is no row with a count of zero.
Filtering with date literals
Date filters are one of the most common uses of WHERE in aggregate queries. They keep a report to a sensible window and keep the scanned row count down.
SELECT StageName, COUNT(Id) cnt
FROM Opportunity
WHERE CloseDate = LAST_N_DAYS:90
GROUP BY StageNameDate literals such as THIS_YEAR, LAST_N_DAYS:90, and THIS_FISCAL_QUARTER are evaluated by the platform at query time. Later chapters cover grouping by date parts, such as CALENDAR_YEAR(CloseDate). Filtering by date in WHERE and grouping by a date part are separate steps, and you often use both in one query.
Limits and performance
Aggregate queries still run under governor limits. In Apex, the number of records a query processes can count toward the limit on total rows retrieved, even though only a few grouped rows come back. A broad aggregate over a very large object can fail even when the result has three rows.
A selective WHERE helps in two ways:
- It reduces how many records the platform must read and group.
- On large objects, it lets the platform use an index when the filter is on an indexed field such as Id, a lookup, or a date field like CreatedDate.
Filters that are not selective, such as WHERE IsDeleted = false or a negative test like != on a common value, may not help performance. For tables with millions of records, consider a filter on an indexed date range and run the query in smaller windows.
Common mistakes
- Putting an aggregate in WHERE. Move that condition to HAVING.
- Putting a record-level condition only in HAVING, which changes the meaning of the totals (see the table above).
- Forgetting that null is a group. Add
!= nullto WHERE if you do not want it. - Assuming empty groups appear. They do not.
- Mixing AND and OR without parentheses.
Exercise
A query must return, for each Industry, the number of accounts with AnnualRevenue above 1000000, and only for industries that have more than 5 such accounts. Write the query, and say which condition belongs in WHERE and which in HAVING.
Show answer
SELECT Industry, COUNT(Id) cnt FROM Account WHERE AnnualRevenue > 1000000 GROUP BY Industry HAVING COUNT(Id) > 5. The AnnualRevenue condition tests a single record, so it belongs in WHERE and runs before grouping. The "more than 5" condition tests a count for a whole group, so it belongs in HAVING.
Exercise
An account has two open opportunities (20000 and 30000) and one closed opportunity (100000). What total does SELECT AccountId, SUM(Amount) total FROM Opportunity GROUP BY AccountId return for that account? What total do you get if you add WHERE IsClosed = false?
Show answer
Without the WHERE clause the total is 150000, because all three records are grouped. With WHERE IsClosed = false the closed record is removed before grouping, so the total is 50000.