Development questions
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).
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
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?