+ Start a Discussion
himanshu huske 7himanshu huske 7 

Soql SubQuery

Please explain me soql subQuery.
when and how to use it in Apex Code(triggers) ?
in Map and in List
give me some examples
Amit Jadhav 13Amit Jadhav 13
Select id (Select id, Name From Contact ) From Account

Example of SubQuery Parent To Child

Select Id , Name, AccountId From Contact

Example of SubQuery child to Parent


thanks!

Regards,

Amit Jadhav 
Ajay K DubediAjay K Dubedi
Hi Himanshu,

Use bellow code for Soql SubQuery it may helpful for you

List<Account> accList = new List<Account>();
accList = [SELECT Id, Name, ( SELECT LastName FROM Contacts ) FROM Account LIMIT 10];
System.debug('accList-->'+accList);

Map<Id, Account> accMap = new Map<Id, Account>(accList);
System.debug('accMap-->'+accMap);

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Deepali KulshresthaDeepali Kulshrestha
Hi himanshu,

Query parent-to-child, which are almost always one-to-many. Specify these relationships using a subquery (enclosed in parentheses), where the initial member of the FROM clause in the subquery is related to the initial member of the outer query FROM clause.

Example of subquery 

SELECT Name,
  (
    SELECT LastName
    FROM Contacts
  )
FROM Account

The query returns the name for all the accounts, and each account, the last name of each contact.

I suggest to visit this link, it will help you in understand subquery in the map and subquery in list:-

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_using.htm

https://salesforce.stackexchange.com/questions/218821/how-to-loop-trough-subquery-relations-map-and-put-all-in-1-map

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.