Generating Dynamic SOQL Query in Apex

Generating a Dynamic SOQL query in Apex refers to the creation of a SOQL string at runtime with Apex code. Dynamic SOLQ enables the user to create more flexible applications, we can create a search based on input from an end-user and update records with varying field names. To create a Dynamic SOQL in Salesforce at run time, use the database query function, in one of the following methods:

  • Return a single sObject when the query returns a single record.
sObject s = Database.query(string_limit_1);
  • Return a list of sObjects when the query returns more than a single record.
List<sObject> sobjList = Database.query(string);

Database.query() can be used wherever an inline SOQl query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOQL queries are processed.

Dynamic SOQL in Apex results can be specified as concrete sObjects, such as Account or MycustomObject_c, or as the generic sObject data type. At runtime, the system validates that the type of the query matches the declared type of the variable. If the query does not return the correct sObject type, a runtime error is thrown. This means you do not need to cast from a generic sObject to a concrete sObject.

Generating Dynamic SOQL Query in Apex

In the example below, we will generate a dynamic SOQl query in Apex, here we use the SOQL query to fetch all fields of the account. We have added one ‘Fetch Account’ button on-page. When we will click on this button all fields of account objects are fetched using SOQL query. We have also shown the SOQL query in the Visualforce page result.

<apex:page controller="selectAllSOQLExampleController" tabStyle="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Fetch Accounts" action="{!fetch}"/>
            <apex:pageBlockSection columns="1" title="Dynamic SOQL Query" collapsible="false">
                <apex:outputText value="{!query}">
            <apex:pageBlockSection title="Account table" columns="1" collapsible="false">
                <apex:pageBlockTable value="{!accList}" var="acc">
                    <apex:column value="{!}"/>
                    <apex:column value="{!}"/>
                    <apex:column value="{!acc.rating}"/>
                    <apex:column value="{!acc.industry}"/>
                    <apex:column value="{!acc.accountnumber}"/>


When we will click on this button all fields of account objects are fetched using SOQL query.

Scroll to Top