Write a SOQL query to fetch Accounts that have more than 5 Contacts (SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) > 5).
Answer
Group Contacts by AccountId and use HAVING to keep only groups with more than five Contacts.
soql
SELECT AccountId, COUNT(Id) total FROM Contact
WHERE AccountId != null
GROUP BY AccountId
HAVING COUNT(Id) > 5
To return the Account details too, put this in a semi-join: SELECT Id, Name FROM Account WHERE Id IN (...) is not allowed with HAVING in the subquery, so query the Account Ids in Apex from the AggregateResult first.
soqlscenarioaggregatehaving