dynamic query in apex

Sometimes we need to write a query depending on various conditions. We can write a string and then execute that string as a query using "database.Query" method.

Many times we also need to form query where in we need to put the fields in query dynamically, in such a scenario we can use field set and then form the query. This dynamic soql query example in salesforce will teach you to build a query using a string. You can use variables, dynamically add on fields and so on. On similar grounds you can also build dynamic sosl query in salesforce.

So as to fire the query you will have to use database.query apex method and append in the string query within brackets as shown in code below.

You need to form the query as string and then execute it as below:

 Public void DynamicQueryFun(){
   String QueryString;
   QueryString = 'Select Name,AccountNumber,AccountSource,Type from Account limit 10';
   List<sObject> accList = Database.Query(QueryString);
   System.debug('--Account List--'+accList);

Put your fields in fieldset and then form your query as below.
** I have created a fieldset named "AccontractField_Set" and then used it to form my query in below example:

  Public void DynamicQueryWithFieldset(){
   //form query from fields in fieldset
    String Querystring = 'select ';
    String fieldsApiNames;
    for(Schema.FieldSetMember fld :SObjectType.account.FieldSets.AccontractField_Set.getFields()) {
        Querystring += fld.getFieldPath() + ', ';
    Querystring += 'id from account';
    System.debug('**Query string**'+ Querystring );
    List<sObject> accList = Database.query(Querystring);  
    System.debug('--Account List--'+accList);

Note: only variable references are allowed in dynamic soql/sosl. You could visit here for details


  1. Hi Yoganand, could you please explain how the above example is to be used ? does it need to be called from a vf page ?

  2. I am not understand properly? what is exactly difference between simple query database.query..?