Well Salesforce Database.query has a unique feature that allows us to append the bind variable inside the Query string. All the variables that is included in the query string automatically calculated and are replaced by appropriate values.

For Example

String accName ='Test Account';
String queryStr = 'SELECT Id FROM Account WHERE Name=:accName';
List<Account> accList = Database.query(queryStr);

The above code works well. Was wondering if there is a method or API that is exposed SF using which we can get the compiled string or the generated query.

I know this can be done by creating template and using String.format() to generate the string Or can use a String with appended variables. Just wondering if it is possible to get the compiled string?


Good question! But I doubt it and I will be surprised if SF ever decides to expose such method.

Binding variables like that to SQL / SOQL ("prepared statements") is a common method to protect yourself against SQL injections plus it's a performance benefit. Database doesn't have to parse different queries to determine what's the best execution plan, order of joins in the tables etc - it can recognize that this query is essentially same as something issued 5 mins ago, just with slightly different data bound to it.

Plus such "flattened" query might turn out to be > 10K characters long which means it's unusable for us anyway ;)

I can think of one place where it'd be useful though - everywhere we switch context so the String with query might travel but bound variables are lost (think about @future or the jump between batch constructor, start() and execute(). QueryLocators aren't serializable so Database.Stateful doesn't help... I don't know, probably some interesting bugs would lurk if we could do it ;)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.