Salesforce Decode
Salesforcedecode
Back to questions
ApexIntermediateaggregatesoqlreporting

Use AggregateResult and GROUP BY efficiently in reporting Apex

Real World Scenario

Executive dashboard Apex aggregates Opportunity amounts by region but hits query row limit.

Expected Answer

• Push aggregation to SOQL GROUP BY not Apex loops • Filter selective date range on indexed CloseDate • AggregateResult iterate for grouped sums counts • Roll-up summary fields where possible avoiding query entirely • CRM Analytics for heavy aggregates instead of real-time Apex • Cache aggregate results with TTL for dashboard • Query only grouped fields not full records

Follow-Up Questions & Answers

Click to expand — each follow-up includes a direct, interview-ready answer

Stay within limits by: Push aggregation to SOQL GROUP BY not Apex loops. Bulkify everything — never query or DML in loops. AggregateResult iterate for grouped sums counts. If you loop records to sum in Apex, you already lost—GROUP BY or roll-up first. Balance speed of delivery with maintainability.

Architect Perspective

If you loop records to sum in Apex, you already lost—GROUP BY or roll-up first.