+ Start a Discussion
Davide BreviDavide Brevi 

SOQL relationship aggregate query

Hi to everybody,
I need to aggregate some information from a Parent to Child Relationship Query.

For example, with the following basic query:
SELECT Account.Name,(SELECT Contact.Name FROM contacts) FROM Account

I'd like to count the number of contacts for a specific account.
Is that possible?

Thank you!

ShirishaShirisha (Salesforce Developers) 
Hi Davide,


I don't think we can use direct SOQL query to get the count of contacts related to an account.However,you can create the trigger to get the total number using the below sample code:



Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Hi there you can try the below query.
select count(id) from Contact group by Accountid
Hope this helps!
Davide BreviDavide Brevi
Thanks Shirisha ,
I can't use a trigger. I need to extract data from workbench...

Best Regards
Maharajan CMaharajan C
Hi Davide,

If you want the Count of Childs in workbench yes we can do that by using below queries.  

 The below query will count the number of contacts for a specific account  based on the Account Id. 

select AccountId, count(Id) from Contact group by AccountId

If you want to use the Account Name to group the contacts then use the below Query

select Account.Name, count(Id) from Contact group by Account.Name