Site icon WedgeCommerce

Prevent hitting soql query limit APEX

Any Salesforce developer must be knowing about the governor limits that the platform imposes on us. Like the number of SOQL rows that could be fetched or the number of SOQL queries that we can make. These limits make it hard to work with bulk data. However, there is something that we can do to make the process easier and work with these limits. Here I am going to explain about working the SOQL query limit. We won’t be bypassing this limit, what we will do is check whenever our code has reached this limit and break the loop, or the execution whichever is required.

APEX Class

public class queryCount {
	
    public static void main(){
        while(true){
            account acc = [select id from account limit 1];
            system.debug(Limits.getQueries());
            if(Limits.getQueries() >= Limits.getLimitQueries()){
                break;
            }
        }
    }
}

In this Code, we have created a class queryCount as we will be counting the number of queries in it. We have a function which is public static. You can name the function anything, however, I have named it main like we do in JAVA. Now moving on this class uses the Limits class to get the number of queries fired till now, with the help of the function getQueries(). This function returns the total number of queries fired in the current execution, i.e. it will tell the total number of queries even if the execution has caused any trigger to initiate. The other function tells us about the total limit imposed by salesforce. Using a function like this instead of hardcoding the limit makes us cope up in case of updates in the governor limits.

To run this class go to the developer console and write this code in the anonymous window:

queryCount.main();

You can update the function name with your selected function name for the static function. Once this is done look at the generated log. It will show that the execution would have had stopped at the imposed governor limit.

Support

That’s all about preventing the code from hitting the governor limits in salesforce APEX, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views about this blog in the comments section below.

Exit mobile version