In my apex code i have a variable resultField and a List<Id> objIds. What i need is a List<My_Obj__c> objs = [select Id, :resultField from My_Obj__c where Id in :objIds];. This is not working because apparantly i can't specify :resultField even though :objIds work in the query. Is there a way to do it other than string concatinations.

  • @RahulSharma i am trying to select a second field dynamically from variable resultField. That's why there is that , – Gurbakhshish Singh Feb 28 '18 at 19:52

You cannot use Apex bindings in the SELECT or FROM clauses of a SOQL query. Bindings are available in the WHERE clause.

You'll need to use Dynamic SOQL to construct your query as a string concatenation, as you mention - there's not another way to build a query with dynamic values in the SELECT clause.

  • will it let me do Database.query('select Id, ' + resultField + ' from My_Obj__c where Id in :objIds'). Will it let me bind :objIds – Gurbakhshish Singh Feb 28 '18 at 19:50
  • Yes. You can still do simple binding to Apex variables. – David Reed Feb 28 '18 at 19:55

Salesforce only takes bind variable in WHERE clause and not in the SELECT statement.

So, you need to perform String concatenation.

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.