SOQLWhat are Dynamic Queries in SALESFORCE?
A dynamic query is a SOQL or SOSL query which can be constructed and executed at runtime. It is the process of constructing the query string consisting of the fields to be retrieved and the WHERE clauses, based upon certain conditions.

SOQL – Salesforce Object Query Language
SOSL – Salesforce Object Search Language

Here is an example of Dynamic SOQL:
General class which runs the query

Public class DynamicQueryUtility
// Function to run the query
Public List runQuery(String objname, String[] fieldnames, String condition)
List queryresult;
String fieldslist = '';
// Generate the fieldslist from the string array
if (fieldnames != NULL)
if(fieldnames.size() > 0)
for (Integer i=0; i < fieldnames.size(); i++)
if( i <= (fieldnames.size() - 2))
fieldslist = fieldslist+fieldnames[i]+',';
fieldslist = fieldslist+fieldnames[i];
// Construct the query string
String soqlquery = 'Select '+fieldslist+' from '+objname+' '+condition;
// Run the query
queryresult = Database.query(soqlquery);
return queryresult;

To Call the Above Class:

// Construct the list of fields
String[] fieldList = new List<String>{'FirstName','LastName','Id'};
// Initialte a new variable of the general utility class
DynamicQueryUtility conRes = new DynamicQueryUtility();
// Call the runquery method to execute the query. Note that the condition has to be passed as an empty string if you do not have any condition
Contact[] contactResult = conRes.runQuery('Contact', fieldList, '');
system.debug('The query result is::'+contactResult);

Salesforce Notes about Dynamic Query:

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply

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