SOQL query count of contacts with no cases

The below query returns all contacts and their related cases.

SELECT Id, Name, (SELECT Id FROM Cases) FROM Contact

To get the count of related cases along with all contacts, you would need to handle this in Apex. SOQL does not allow counting directly in subqueries.

List listOfContacts = [SELECT Id, Name, (SELECT Id FROM Cases) FROM Contact];

for (Contact con : listOfContacts) {
    Integer casesRelatedToContact = con.Cases.size();
    System.debug('Contact Name: ' + con.Name + ', Number of cases related to contact: ' + casesRelatedToContact);
}

Read more here: Source link