I have the following query, which uses 2 variables, the record type ID and a list of comma separated fields.

    Id schoolRecordTypeId = SchoolRecordTypeId; 
    String fields = getFields();   //e.g. 'Name, Type, Stage__c, '
    String query = 'SELECT ' + fields + ' id FROM Account WHERE RecordTypeId = :schoolRecordTypeId';

The above query works, but the below one doesn't (Note use of :fields). Why would the above work and the below doesn't?

String query = 'SELECT :fields id FROM Account WHERE RecordTypeId = :schoolRecordTypeId';

1 Answer 1


You can't use Apex binds in the SELECT clause. They're supported in:

  • The search string in FIND clauses.
  • The filter literals in WHERE clauses.
  • The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type.
  • The division names in WITH DIVISION clauses.
  • The numeric value in LIMIT clauses.
  • The numeric value in OFFSET clauses.

You may always concatenate strings to produce a Dynamic SOQL query. For queries with much complexity, I generally recommend formatting with String.format() to make the query's structure clear and avoid hard-to-spot problems when the creation logic gets too complicated.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .