Dealing with AggregateResult

Apex Jan 18, 2015

Ever worked with Aggregate Functions like count(), sum().... and find troube with parsing aggregateResults, here I try to explain in following explain

So When ever you use AggregateFunctions in SOQL return type will be of Type AggregateResult (this is mandatory)

While querying AggregateResult in a loop Use alias naming which makes our life easy, check example below

for(AggregateResult u : [SELECT Profile.UserLicense.Name lName, Count(Id) uCount from User GROUP BY Profile.userLicense.Name]){
    system.debug(u.get('lName')); // get user Profile Name
    system.debug(u.get('uCount')); // get User count for that profile name

In above debug statements I used u.get('lName'), here

  1. lName is alias for Profile.UserLIcense.Name
  2. uName is alias for Count(Id)

If you wont use alias naming then you might up ending using exp0, exp1 which is default used by apex with an order from left to right.

So dont make your queries complex using exp0, exp1 rather than use Alias as I shown

For more information on Working with Aggreagate Results click here

Happy Coding!!

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap