Search code examples
apexsoql

SOQL Query in loop


The following APEX code:

for (List<MyObject__c> list : [select id,some_fields from MyObject__c]) {
  for (MyObject__c item : list) {
    //do stuff
  }
}

Is a standard pattern for processing large quantitues of data - it will automatically break up a large result set into chucks of 200 records, so each List will contain 200 objects.

Is there any difference between the above approach, and below:

for (List<MyObject__c> list : Database.query('select...')) {
  for (MyObject__c item : list) {
    //do stuff
  }
}

used when the SOQL needs to by dynamic?

I have been told that the 2nd approach is losing data, but I'm not sure of the details, and the challenge is to work out why, and to prevent data loss.


Solution

  • Where did you read that using Dynamic SOQL will result in data loss in this scenario? This is untrue AFAIK. The static Database.query() method behaves exactly the same as static SOQL, except for a few small differences.

    To answer your first question, the main difference between your approaches is that the first is static (the query is fixed), and the second allows you to dynamically define the query, as the name suggests. Using your second approach with Dynamic SOQL will still chunk the result records for you.

    This difference does lead to some other subtle considerations - Dynamic SOQL doesn't support variable bindings other than basic operations. See Daniel Ballinger's idea for this feature here. I also need to add the necessary security caveat - if you're using Dynamic SOQL, do not construct the query based on input, as that would render your application vulnerable to SOQL injection.

    Also, I'm just curious, what is your use case/how large of quantities of data are you talking about here? It might be better to use batch Apex, depending on your requirement.