How to write Dynamic Soql Query .

Before going to code we learn about  Dynamic Soql Query .
Dynamic Soql:

Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code. Sometimes we need to query data on the based of input from end users or update records with varying field names. Here to achieve  this requirement we use  dynamic  Soql queries.

To create a Dynamic Soql Query at run time,  we use  database query method.

To create a dyanmic soql  you need to keeps

  1. query as a string
  2.  Execute  query string using Database.query method.

Here is the Duanmic soql query example  in this example we are getting  soql fields from a fieldset.

// here first we  take query as a string 
String query = 'SELECT ';

// now get fields from fieldset iterate over fieldset and concate the field to query string
for(Schema.FieldSetMember f : SObjectType.opportunity.FieldSets.Yourfieldset_name.getFields())
query += f.getFieldPath() + ', ';
query += 'id FROM Opportunity where id in:oppids';

// execute query string using Database.query
list<opportunity> oppor = Database.Query(query);


Hits: 575

Share Post

You may also like...

2 Responses

  1. sneh says:

    It was helpful for me.
    thank u.

  2. nitya gupta says:

    very helpful thanx alot

Leave a Reply

Your email address will not be published. Required fields are marked *