Is there a way to make dynamic apex field references bind a reference to the fields? To illustrate the question, let's take the following example query:

String query = "SELECT myField__c FROM Account"

In the example, the field myField__c is not strongly referenced. This means you can delete the field from SFDC (without getting a field deletion prevention error stating what it's tied to) and blow up the apex next time the query is run.

I'm looking for a way to prevent the deletion of a field called out in a dynamic query (in this example: myfield__c) while still maintaining the dynamic referencing aspect of the query.

Obviously, if the following apex existed in a class somewhere, the system would give an error if someone tried to delete myfield__c from the Account object:

List<Account> accounts = [SELECT myfield__c FROM Account];

But I would like to prevent deletion of the field when myfield__c is referenced like so:

String query = "SELECT myField__c FROM Account"

Thanks in advance.


Absolutely you can. Just merge in strings that you build from SObjectField. I would recommend using String.join. Simple example:

List<String> fields = new List<String>
Database.query('SELECT ' + String.join(fields, ',') + ' FROM Account');
  • That works, but it defeats the purpose of dynamic. – user3430245 Apr 4 '18 at 19:35
  • How does it defeat the purpose... you've given very little detail in your question. – Adrian Larson Apr 4 '18 at 20:13

You could use a dummy method to keep a solid reference:

public static void keepReference() {
  Object[] fields = new Object[] {
    Account.MyField__c, Account.MyOtherField__c

Personally, I'd advise against using dynamic queries if you can help it, since they are inherently fragile. Dynamic queries should be considered a last resort.

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.