SOQL query that counts the number of active Contacts for each Account in a set

This example shows how to use Set effectively to count active contacts for each account using SOQL query without duplicate records.

Set<Id> stAccIds = new Set<Id>(); //Suppose this set has Account Ids 

Map<Id,Integer> accountIdWithContactCount = new Map<Id,Integer>();

 for(Account acc : [SELECT Id,Name,(SELECT Id FROM Contacts WHERE Active__c = true) FROM AccountWHERE Id IN :stAccIds])

{    

accountIdWithContactCount.put(acc.Id,acc.Contacts.size()); 

}

Now this map ‘accountIdWithContactCount’ will have count of contacts for each account

You can get the count by passing account Id
 Integer count = accountIdWithContactCount.get(accId);

Technical Knowledge Gain :-

  • By going through this concept, you can know the usage of dynamic SOQL query in an apex code.
  • Collections concept Map used to demonstrate how it is helpful in storing and retrieving a key value pair effectively for one-many relationships.
  • Collections concept Set is used to avoid duplicate ID values to identify unique active contact records for each account.

Be the first to comment

Leave a Reply

Your email address will not be published.


*