You are here:
ApexGuru Antipattern: Aggregating Records in Apex
SOQL queries that manually compute aggregate functions in Apex are inefficient and lead to performance issues. This approach wastes CPU resources and results in bloated, less readable code that's harder to maintain. Instead, use SOQL’s built-in aggregate functions like SUM(), AVG(), COUNT(), and COUNT_DISTINCT() to perform the work at the database level.
Scope
Detection only
Detection Example
The developer is querying individual records and performing the aggregation (summing
Points__c) manually in Apex, likely within a loop per user, rather than
letting the database engine handle the aggregation efficiently.
for(User u : allActiveUsers){
Decimal i = 0;
List<Achievement__c> achievements = [
SELECT Id, Points__c, User__c, Statut__c, CreatedDate
FROM Achievement__c
WHERE Status__c = 'Valid'
AND CreatedDate > :currentChallenge.StartDate__c
];
for(Achievement__c achievement: achievements){
i += achievement.Points__c;
}
System.debug('Total: ' + i);
}Recommendation
Use SOQL aggregate functions like SUM() to shift computation to the database
for better scalability.
for(User u : allActiveUsers){
Decimal i = 0;
AggregateResult ar = [
SELECT SUM(Points__c) totalPoints
FROM Achievement__c
WHERE Status__c = 'Valid'
AND CreatedDate > :currentChallenge.StartDate__c
AND User__c = :u.Id
];
if(ar != null && ar.get('totalPoints') != null){
i = (Decimal)ar.get('totalPoints');
}
System.debug('Total: ' + i);
}