Redeem Now
Read More
Read now
Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    Execute a dynamically created query in APEX

    Any Salesforce developer must be familiar with SOQL queries. SOQL as we all know is the Salesforce’s version of SQL. It’s full form translates to Salesforce Object Query Language. We have an idea about directly using query in APEX by writing the query in between ‘[‘ and ‘]’. However there is a limitation to the method i.e. queries created are a lot restricted and only available method to use variables is using them in where clause. We cannot use columns as variables, neither the conditions to be set or anything else. For this purpose we require a query which we can be generated as a string and then use it. This is what I am going to demonstrate to you how to execute a dynamic query in APEX.

    Sample code (APEX)

    In this class we have done everything like any normal APEX class, only difference is the getRecords() function which has Database.query() function. This function executes a string query, at the cost of total number of rows we can fetch in one execution of the class. The limit is 10,000 as compared to the 50,000 limit of the normal static query.

    Sample code (Visualforce)

    In this example as you can see that we have not used the column name, however we have fetched it. That is because, for sObject the column name and value are created as a map at runtime, and hence we have to create a wrapper class to use that data. Rest everything is same.



    That’s all about Executing Dynamic Queries, for any further queries feel free to add a ticket at:

    Or let us know your views on how to make this code better, in comments section below.

    . . .

    Leave a Comment

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


  • Jagan
    How to set limit as variable and dynamically user assign value while page is running
  • Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again

    Table of Content

    Hide Index