I have a

 Map<String, String> objectNameWithQueryString;

objectNameWithQueryString consists of 'ObjectAPIName' as the key and a 'soql query string as the value'.

My requirement is to perform dynamic queries against each object and story all the results from all object in an SObject List.

However, it seems to me that the only way to so this is to use dynamic SOQL within for loop, which is not the best practise.

Is there any other way to perform this?

  • Depends upon your use case, if you wanna query all of them ... then it does not matter whther it's in for loop or 'n' time get operation ...may be you can explain your use case then you can get a better approach here.
    – Ayub
    Jan 28, 2020 at 10:32

1 Answer 1


SOQL queries are inherently single-object. You are correct that there is no way to implement this requirement as written without using iteration.

However, this requirement itself is rather suspect. If you have a need to perform the same query across multiple objects, you should at least evaluating using SOSL rather than SOQL.

If you simply need to perform multiple unrelated queries across distinct objects, it's not clear what you gain by centralizing that query activity in a single generic method using Dynamic SOQL. It is clear, however, what you lose by doing so:

  • Compile-time checking of fields and query syntax.
  • Static dependencies between your code and schema, ensuring that the Metadata API can check those relationships at deployment time.
  • The ability to use Apex binds in your queries.
  • The ability to use Selector-layer classes on a per-object basis.
  • You may have more difficulty tracking where you need to sanitize user input to avoid SOQL injection.
  • If you use any kind of static analyzer, it's going to complain about the SOQL in a loop.

I would push back strongly on adopting this implementation pattern.

  • I need to to SOQLs because I need to search lookup fields values. Had they been normal text values, i would have most definitely used SOSL. As a result of this I am stuck
    – Madhurima
    Jan 28, 2020 at 17:39

You must log in to answer this question.

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