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