When reading Apex code, there are at least two instances where SFDC is doing something more than the is immediately apparent given the syntax of the code, both of which somehow relate to SOQL:

  1. SOQL-for-Loops:

Whether we use the traditional or dynamic SOQL, the return type is a normally a List. However, if we put the query immediately after the colon of a for-loop, where a collection we would iterate over normally goes, it appears that the method used for record retrieval is different and has different limitations.

String s = 'Acme';
for (Account a : [SELECT Id, Name from Account
                  where Name LIKE :(s+'%')]) {
    // Your code
  1. Binding Variables

Normally, a string literal will be interpreted exactly as its written. If I want to include a value from a variable, either I need to break out of the literal to add the value, or I need to use String.format(). However, when performing dynamic SOQL, I can include the variable directly in my string:

String myTestString = 'TestName';
List<sObject> sobjList 
   = Database.query(
     'SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString'

I'm wondering:

  1. Are there other instances where Apex will do something which wouldn't be immediately obvious from a straight reading of the code?

  2. Can we implement and leverage similar functionality elsewhere in our code somehow? (Which is not the same question as to whether we should. Generally, I'm inclined to believe we shouldn't since it would make the code more difficult to maintain, but I like to know all the tools available to me.)

  • Mixing together a general programming language compiler with a database query compiler... not really "deep magic" IMHO. – Keith C May 25 '18 at 8:22
  • Of course, the implementation details aren't truly magic, but the typical Salesforce developer has no way to touch the compilers and only limited information about what it will do, and in these instances, we find them operating outside of normal Apex behaviour, but we don't know any details towards how or why, just that it works. – Brian Kessler May 25 '18 at 8:32