function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Prakhyat sapraPrakhyat sapra 

what is the query for getting account whose related contact is more then 2

what is the query for getting account whose related contact is more then 2
mukesh guptamukesh gupta
Hi Prakhyat,

Please use below code:-


First option:-
List<AggregateResult> results=[SELECT count(Id) FROM Contact Where AccountID='00141000015cS58']; //count() return AggregateResult type value
integer total_contact = Integer.valueOf(results[0].get('expr0') + '');
system.debug('total contact of Internal Queries : '+total_contact);

Second Option:-
 
List<Account> modAccounts = [Select Name, (Select Id from Contacts) from Account WHERE Id in: accIds ];

for (Account a: modAccounts) {
List<Contact> con = a.Contacts;
System.debug('Account:' + a.Name + ' No. of Contacts: '+ con.size());

}
}


if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
AnkaiahAnkaiah (Salesforce Developers) 
Hi Prakhyat,

try with below code.
set<id> accids = new set<id>();

List<account> acclist = [select id,(select id from contacts where accountid!=null) from account];

for(account acc:acclist){
    
    if(acc.contacts.size()>2){
      accids.add(acc.id) ; 
    }
}

system.debug('accids='+accids);

If this helps, Please mark it as best answer.

Thanks!!
Rohit Bhalla 21Rohit Bhalla 21

Hi Prakhyat,

Use the below SOQL to find related contacts more than 2

SELECT AccountId, COUNT(Id)
FROM Contact
GROUP BY AccountId
HAVING COUNT(Id) > 2