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
RaviKumarRaviKumar 

Parent to Child(Account to Contact) soql query

For account there is related list of contacts. I want to know that how many contacts are there for that account.
Query should be Parent To Child like  
" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Use Case: because I want to write trigger on Account and limits that for every account should not more than 3 contacts.

Thanks in advance.
Best Answer chosen by RaviKumar
Suneel#8Suneel#8

" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Your query is right.You can access number of contacts corresponding to a specific account as below

for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
      System.debug('Account name:'+a.name+'  Number of contacts:'+a.contacts.size());
}

All Answers

Suneel#8Suneel#8

" SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account"
Your query is right.You can access number of contacts corresponding to a specific account as below

for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
      System.debug('Account name:'+a.name+'  Number of contacts:'+a.contacts.size());
}
This was selected as the best answer
RaviKumarRaviKumar
Thank u @Suneel#8 for your reply.
I have been trying to resolve these issue from long time. U provides an exact Solution for my Issue. I am very glad to have your reply.

And i have small clarification in that
for(Account a: [SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){
}

In the above for loop we are iterating through the QUERY "[SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]" But what if we have for loop like
for(Account a: Trigger.new){
}

In that "Trigger.new" we are not querying contacts "SELECT Name, ( SELECT LastName FROM Contacts ) FROM Account]){   } "
So while I'm writing in the Trigger
 
for(Account a : Trigger.new){
               sss.add(a.Id);
           }
 List<Account> aaa =  [select id, name,(Select id from Contacts) from Account where id in: sss ];
 for(Account a : aaa){
      If(a.contacts.size() <= 3 ){
       }
}

Is ther any way to reduce the code.

Once again Thank u for your information.....
Suneel#8Suneel#8
You can make use of trigger.newMap trigger context variable to get Id's of updated records.trigger.newmap is an id to object mapping of all the records that were updated in the trigger.You can read more about trigger context variable in below link

List<Account> aaa=[select id,name,(select id from Contacts) from Account where id in :trigger.newMap.keySet()];

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables.htm