Sub topic 2
Naming Aggregate Results with Aliases
Assume you know basic SOQL, Salesforce objects and fields, and basic Apex loops and casting. Aggregate queries return summary rows instead of individual records. An alias is a name you assign to a calculated value, such as a count or sum.
Naming Results with Aliases
Use an alias after an aggregate expression. The alias makes the result easier to read and gives Apex a stable key for retrieving it.
SELECT StageName, COUNT(Id) opportunityCount, SUM(Amount) totalAmount
FROM Opportunity
GROUP BY StageNameEach result has a StageName, an opportunityCount, and a totalAmount. Without aliases, calculated fields can have awkward generated names. Always alias aggregate expressions that Apex will read.
Reading Results with AggregateResult
In Apex, a grouped SOQL query returns a list of AggregateResult objects. Call get() with the grouped field name or aggregate alias, then cast the returned value.
for (AggregateResult row : [
SELECT StageName, COUNT(Id) opportunityCount, SUM(Amount) totalAmount
FROM Opportunity
GROUP BY StageName
]) {
String stage = (String) row.get('StageName');
Integer count = (Integer) row.get('opportunityCount');
Decimal amount = (Decimal) row.get('totalAmount');
System.debug(stage + ': ' + count + ' opportunities, total ' + amount);
}The string passed to get() must exactly match the field name or alias. A misspelled alias returns null, which can cause later errors.
Filtering Rows Before Grouping
WHERE filters individual records before Salesforce forms groups. Use it when records should not participate in the calculation.
SELECT AccountId, SUM(Amount) totalAmount
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountIdThis calculates open opportunity totals only.
Filtering Groups with HAVING
HAVING filters completed groups. Use it when the condition depends on an aggregate value.
SELECT AccountId, SUM(Amount) totalAmount
FROM Opportunity
WHERE IsClosed = false
GROUP BY AccountId
HAVING SUM(Amount) > 100000WHERE removes rows first. HAVING removes groups afterward.
Exercise
Which clause finds accounts with more than five open opportunities: WHERE or HAVING?
Show answer
HAVING, because the condition uses COUNT(Id), an aggregate calculated per group.