Share Your Experience With Others

Aggregate Functions in SOQL

  • AggregateResult is a read-only sObject and is only used for query results.
List<AggregateResult> results = [
  SELECT COUNT(Id) numAccounts, Name
  FROM Account
  GROUP BY Name
  HAVING COUNT(Id) > 1
];

results[0].get('numAccounts');
  • Aggregate results represent more than one record, we are not able to include the Ids of the records.
  • Notice that we used the alias numAccounts.
  • If you don’t include an alias for aggregated fields, then Salesforce will assign one following the pattern expr0 where 0will be incremented for each additional non-aliased aggregate field.
  • For aggregate queries you can use an alias on any field in the query and it makes accessing them via apex much easier.
  • Use aggregate functions in a GROUP BY clause in SOQL queries to generate reports for analysis. Aggregate functions include AVG() , COUNT() , MIN() , MAX() , SUM() , and more.
  • While all aggregate functions could be used without the GROUP BY clause, the whole point is to use the GROUP BY clause. That clause serves as the place where you’ll define the condition on how to create a group.
  • When the group is created, you’ll calculate aggregated values.
  • You can’t use a LIMIT clause in a query that uses an aggregate function, but does not use a GROUP BY clause. For example, the following query is invalid: SELECT MAX(CreatedDate) FROM Account LIMIT 1
  • But if you write SELECT Count(Id) numContacts,AccountId,Account.Name, FROM Contact GROUP BY AccountId, Account.Name LIMIT 2000 it’s a valid query.
  • All aggregate functions ignore null values, except for COUNT() and COUNT(Id)
  • COUNT(fieldname) is different from COUNT(). COUNT(fieldname) does ignore null values.

Limitations of Aggregate Queries

  • Results cannot be paginated, so you may not be able to process all of your data in some cases. You can use LIMIT and OFFSET to get up to 4000 records in most cases.
  • Subqueries cannot be grouped and aggregate queries cannot include subqueries.
  • You cannot use aggregate queries as the batch job query.
  • Grouping some relationships may cause random unexpected errors with no apparent reason.

Leave a comment