We have some legacy code in one of Salesforce orgs. While going through code, I encountered this piece of code

  List<query_metadata__c> dyQueries=[select id,query__c,object__c from query_metadata__c];
for(String query:dyQueries) {
        List<Sobject> objResults = new List<Sobject>();
        objResults = Database.query(query);

SOQL queries are getting executed inside for loop which is against best practices. On further diving, I found out that these whole queries are getting fetched from a custom metadata and these queries are of different objects. This query list is going to static. Only 35 or less. No more queries are going to be added.

I was wondering if there is any way we could avoid this query inside for loop. To me they look okay for multiple reasons.

  1. Even if we execute each of these query individually out of for loop that is going to be 35 queries plus unnecessary repetitive code
  2. Since this list is static, no more queries are going to be added so it is always going to be 35 or less.
  3. This code is getting executed inside batch apex so the limit gets increased to 200.

Still, looking out for suggestions, to conform to best practises.

1 Answer 1


This common case that leads to this idea is having a loop over a list of records with a query inside the loop. Works fine initially when there are only a few records but breaks when there are more records. The number of records is indeterminate. And the coding pattern to handle that is usually to move the nested query out of the loop and hold its results in a map that is referenced inside the loop.

Your case requires the 35 queries - there is no other (simple) way to do the work. Here, the number of records is determinate. So personally, I would add a comment explaining why you have made this design choice, and if over time more queries are added resulting in that or other limits being exceeded, refactor then.

Be wary of words like "best" in software that imply that there is one always ideal solution. This post The Law of Demeter Is Not A Dot Counting Exercise about a "law" includes the Martin Fowler comment:

I'd prefer it to be called the Occasionally Useful Suggestion of Demeter

  • Thank you. I was also thinking of same. Jan 20, 2023 at 23:00

You must log in to answer this question.

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