function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DakotaDakota 

SOQL Query account record with count contacts

I am trying to write a single query to get an account record and the count of contacts for the account.  Can this be done?

 

Ex: 

SELECT Name,Id,BillingState, (SELECT count() FROM Contact Where Contact.AccountID = Id) FROM Account WHERE Name like '%Test%'"

 

Thank You

Dakota

 

 

Raumil SetalwadRaumil Setalwad
DakotaDakota

I appreciate the response, however the referred page does not help.  I am looking for the correct sytax for a subquery like my example.

 

 

I want to get a single record from the Account table and get a count on Contact for the Account record.

 

Thank You

 

Dakota 

Ritesh AswaneyRitesh Aswaney

Dont reckon you can do COUNT() in an inner query.

 

This query kinda returns what you're after

 

Select AccountId, Count(Name) from Contact group by AccountId

 

If you're just after how to formulate an inner query, then here goes

 

Select Id, Name, (Select Id, Name from Contacts) from Account

 

If you want to reference a bind variable in your query, then it must be prefixed with a colon, eg

 

Select Id, Name, (Select Id, Name from Contacts) from Account where Id = :accountId