function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Brijesh KumarBrijesh Kumar 

how can solve System.Exception: Too many SOQL queries: 101

Hi
I have found an exception :

System.Exception: Too many SOQL queries: 101
I explain my problem with simple example.This example look like as my application:

public class class1
{
    void show()
    {
        for(Integer i=0;i<5;i++)
        {
            Double d1=class2.getData();
            Double d2=class3.getData();
        }
    }
public pageReference save()
{
show();
}
}




// Another Apex class


global class class2
{
    Webservice static Double getData()
    {
        Double d=0.0;
        for(Integer i=0;i<12;i++)
        {
            // perform SOQL Query
            //just like......
            for(Object__ c:[select id__c from Object__c])
            {
                d=c.id__c;
            }
        }
        return d;
    }
}

// Another Apex class



global class class3
{
   
Webservice static Double getData()
    {
        Double d=0.0;
        for(Integer i=0;i<12;i++)
        {
            // perform SOQL Query
            //just like......
            for(Object__ c:[select id__c from Object__c])
            {
                d=c.id__c;
            }
        }
        return d;
    }
}


When i call save() from visual force page i am getting exception Too many SOQL queries.
Please solve my problem.

Thanks & Regards
Brijesh Kumar Baser

Praetorian65Praetorian65
You need to use a bulk SOQL query to get all the records from your custom table first, then look for the IDs in the list (or create a Map, then do it). ATM you are doing a single query many many times.
aalbertaalbert
To elaborate, you want to move your SOQL queries outside of any FOR loops to avoid hitting this governor limit. You can pass in binding variables into the WHERE clause to help grab a set of data. Since a SOQL query will happen each iteration of the loop, you will quickly reach the limit of 100 queries (in your example).