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
tc21tc21 

How can I write a single soql statement to retrieve the id, and the number of contacts associated with a particular account if the account has more than four contacts

Priyananth RPriyananth R
Hi,

Account accObj = [SELECT Id, (SELECT Id, FirstName, LastName from Contacts) FROM Account where id = ‘XXXX’];
Access contact :
List<Contact> conList = accObj.Contacts;

Thanks,
Andrew GAndrew G
If you want to limit the SQL statement to ignore Accounts with less than 4 contacts, and you want the query to be a singular string, then you need to do prework.
Basically create a field in the Account record "Contact Count".  Have it populated by a trigger whenever a contact is inserted or deleted.
Then add that field to your query:

Account accObj = [SELECT Id, (SELECT Id, FirstName, LastName from Contacts) FROM Account where id = ‘XXXX’ AND Contact_Count__c >4];

Otherwise, if you use the base query supplied by Priyanth, you are going to need to loop the results and do some counting.


Regards
Andrew