+ Start a Discussion
Cameron SeitzCameron Seitz 

SOQL Query to return Related Objects > 5

I'm currently trying to write a SOQL Query to pull all Accounts that have > 5 related Contact objects. How do I go about counting related objects? 
Pradeep SinghPradeep Singh
Hi, 
Here you can use aggregate functions/query.
Refer below code :-
Map<id,integer> accAgg = new Map<id,integer>();

for(aggregateResult agg :[select count(id) cnt, AccountId from contact Group By AccountId having count(id) > 5]){
    accAgg.put((ID)agg.get('AccountId'),(Integer)agg.get('cnt'));
}
 
Cameron SeitzCameron Seitz
I was able to get the query below to return my desired results. However, it exceeds the limits. I should be able to get the results to a managable amount by adding additional filtering. 
Select AccountId, Count(Id)  from Contact group by AccountId having count(Id) > 5

The additional filtering that I will need will involve a related object. so it will have to look something like
Select AccountId, Count(Id)  from Contact group by AccountId having count(Id) > 5 AND there are no related ts2__Placement__c objects.
How would I go about adding that on or nesting it?