---
schema_version: "1"
id: 4fbf9ba3e763a346fa8968c641ab1acad43412b7330f582dd28bad455d23ea0a
title: "ApexGuru Antipattern: Aggregating Records in Apex"
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/xcloud/264-0-0/apexguru_antipattern_aggregating_in_apex.md
canonical_url: https://help.salesforce.com/s/articleView?id=xcloud.apexguru_antipattern_aggregating_in_apex.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: ab424472143097f4957887b9eab6b39e1d31e7d4486003742216355548ce835e
description: 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.
products:
  - Cross Cloud
release: "264"
---
# 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.

```java
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.

```java
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);
}
```