I have a dynamic soql as below.

string remainingbetquery ='select id,name,uw_Brand__r.Name,Market_Cluster__c,Product_Category_Sub_Division__c from uw_bet__c where (id not in :betfollowed) and (id not in :betowners) ';

query = query + 'and BET__r.Product_Category_Sub_Division__c ='+'\''+categories+'\'';

for some reason its not properly working and returning correct values .

categories is a dynamic picklist generated by code as well.so when user selects a value in front end it gets populated in controller

Updated with controller code for categories

public List<String> categories {
    get {
      if (categories == null) {

        categories = new List<String>();
        Schema.DescribeFieldResult field = uw_bet__C.Product_Category_Sub_Division__c .getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())

      return categories;          

Pagecode for picklist
Category <select id="categories" >
            <option value=""></option>
            <apex:repeat value="{!categories}" var="tech">
              <option value="{!tech}">{!tech}</option>
  • Can you share more of your code? What data type is categories? Dec 10, 2013 at 4:02

1 Answer 1


Instead of the HTML element you'll want to make use of Visualforce's built in components, in this case the apex:selectList tag if you want user input to influence the controller's state.

You also don't seem to need to use dynamic SOQL. If you switch to using pre-compiled SOQL (the [] syntax) you'll gain some additional compile-time validations on your query and benefit from some extra security.

SOQL has a special syntax for binding a variable's value into a query without having to manually perform string manipulation: precede the name of the variable with a : character.

Rewriting your query with both of these changes would look like:

[select id,name,uw_Brand__r.Name,Market_Cluster__c,Product_Category_Sub_Division__c from uw_bet__c where (id not in :betfollowed) and (id not in :betowners) and BET__r.Product_Category_Sub_Division__c = :categories]
  • many thanks for your kind reply.i have used selectoption and now my controller var is getting properly set...what i posted here is a very small portion of a big chunk of code.and my functionally is forcing me to use dynamic soql(a dynamic search usecase)..so is there any way to specify it properly with escape characters and all in the code i posted
    – sfdc99999
    Dec 10, 2013 at 4:48
  • You can use the same :variable syntax with dynamic SOQL, but with a few restrictions (that don't seem applicable to you): salesforce.stackexchange.com/a/3527/60 Dec 10, 2013 at 6:25

You must log in to answer this question.

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