Salesforce Certified Platform Developer free question 5 / 10 · Domain 2: Process Automation and Logic
A developer runs the following SOQL in Apex to read the total Amount for each stage. AggregateResult[] rs = [SELECT StageName, MAX(Amount) big, SUM(Amount) FROM Opportunity GROUP BY StageName]; for (AggregateResult ar : rs) { Object total = ar.get(X); } Which value for X matches the Apex Developer Guide?
- 'expr1'
- 'expr0'
- 'SUM'
- 'Amount'
Show the answer and explanation
Answer: B
Why this is correct
The topic "Working with SOQL Aggregate Functions" says an aggregate field in the SELECT list that has no alias gets an implicit alias in the form exprI. I starts at 0 and increases by one for each aggregate field without an alias. In this query the only aggregate field without an alias is SUM(Amount), so its value is read with ar.get('expr0').
Why the other options are wrong
"'expr1'" … The numbering counts only aggregate fields that have no alias, starting from 0. MAX(Amount) has the alias big, and StageName is not an aggregate field, so SUM(Amount) is the first unaliased aggregate field and gets expr0.
"'Amount'" … Amount is the name of the field the aggregate was computed from, not the name of the sum inside the AggregateResult. Both MAX and SUM use Amount, so it could not tell them apart anyway.
"'SUM'" … An aggregate field without an alias is named in the form exprI, not after the function. The value cannot be fetched by the function name.
Takeaway
A query with an aggregate function returns an array of AggregateResult, a read-only sObject. For readability, give each aggregate field an alias, as in SUM(Amount) total.