I am trying to make it so I do not need to include a SOQL query in my for loop. In the below list, "a" is a list of accounts that I have previously queried.

 List<CustomObject__c> sn = [SELECT Id, Name, Service_Offering__c FROM CustomObject__c WHERE Account__c = :a.Id]; 

 List<String> HealthPlanStrings = New List<String>();

My loops looks like this currently (Please note that Service_Offering__c is a custom object that relates to the CustomObject__c object I am referencing).

for(CustomObject__c snanas : sn){
    Service_Offering__c so = [SELECT Name FROM Service_Offering__c WHERE Id = :snanas.Id];

I would prefer to remove my query from the loop to avoid governor limits, but I am running into issues putting the SOQL query in the parentheses. Below is what I have attempted:

for(Service_Offering__c so : [SELECT Name FROM Service_Offering__c WHERE ID = :sn.Service_Offering__c]){

The message I get states:

Initial term of field expression must be a concrete SObject: List(Services_NaviNetAccountNumbers_Accounts__>;

Is there another way that I need to form my query so that it can loop through each of the service_offerings in the List(CustomObject__c> sn and add their names to the HealthPlanStrings list?

I would greatly appreciate any input.

Thanks, CP

1 Answer 1


you can do it in a single query only as "Service_Offering__c " is a parent to "CustomObject__c".You can use relationship queries to achieve this.

List<CustomObject__c> sn = [SELECT Id, Name, Service_Offering__r.Name FROM CustomObject__c WHERE Account__c = :a.Id]; 

 List<String> HealthPlanStrings = New List<String>();
for(CustomObject__c snanas : sn){
  • That worked stupendously. Many thanks. It says I cannot accept an answer for 2 minutes, but I will certainly accept this ASAP.
    – Chris P
    Feb 3, 2016 at 17:15
  • your welcome :)
    – Nitin
    Feb 3, 2016 at 17:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .