Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

Why is the benefit of using the aggregate query in Salesforce?

Asked by David Piper Feb 8, 2023 681 views 1 answer
Share

About this question

I am wondering if there are any benefits of using Aggregate Query in Salesforce. Let's say we have 2 code snippets here.

Let's say accIdSet is a collection account Id we are working on.

CODE 1 :

for (AggregateResult agg : [
    SELECT Count(ID) cnt, AccountId
    FROM Contact
    WHERE AccountId IN :accIdSet
    GROUP BY AccountId
]) {
    Account acc = new Account(Id = (String) agg.get('AccountId'));
    acc.Total_Contact__c = (Integer) agg.get('cnt');
    updateAccList.add(acc);
}
CODE 2:
for (Account acc : [
    SELECT Id, (
        SELECT Id
        FROM Contacts
    )
    FROM Account
    WHERE Id IN :accIdSet
]) {
    Account accObj = new Account(Id = acc.Id);
    accObj.Total_Contact__c = acc.Contacts.size();
    updateAccList.add(accObj);
}

Both do the same thing, count the number of contacts and update the Total_Contact__c field on the Account record.


I have a basic idea of Aggregate Query and its aggregate functions but are there any benefits of using this.

Your answer

1 Answer

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.