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
srkSFsrkSF 

How to generate SOQL 101 error in for loop?

Hi All,
I have a requirement to generate SOQL 101 error  in a for loop.
Using for loop,generate 100+ SOQL in one transaction.
Generate 101 error.
Using future function,resolve this issue and perform 150 SOQL in one transaction.
Code below is not compiling.
Pls help!!!!

Apex Class:

public class SOQL101Error {
List<Student_Master__c> studentlist = new List<Student_Master__c>();
    studentlist = [SELECT id,Name,First_Name__c,Last_Name__c FROM Student_Master__c];
    for(Student_Master__c sm: studentlist){
       // string query =' select ID,Name from Account ';
    }

}

 
Surya GSurya G
Hi,

Try using LImits class method to check the number of soql issued and based on that call the future method.
Till 100 queries it will run in single transaction, if it is more than 100, it will add the id to the list and call the future method to process rest of SOQL queries
public class SOQL101Error {
List<Student_Master__c> studentlist = new List<Student_Master__c>();
    List<Id> studentIdList = new List<Id>();
    studentlist = [SELECT id,Name,First_Name__c,Last_Name__c FROM Student_Master__c];
    for(Student_Master__c sm: studentlist){
        // check no fo queries issued in single transaction , if it is more than 100 , call future method
        if(Limits.getQueries() < 100) {
       		//write your query
    } else {
        studentIdList.add(sm.id);
        
    }
    }
    if(studentId.size()>0){
        // call future method pass studentIdList as augument and process rest of the query there
    }

}
Thanks
Surya G
 
shekhar gadewar 136shekhar gadewar 136
I'm too late but yeah it can help others.

Generate 101 error as below:

public class Generate101Error {
    public static void soql101Error(){
        List <Account> accList = New List<Account>();
        for(integer i=1 ; i <= 120 ; i++){
            accList = [SELECT Id, Name FROM Account Limit 1];
        }
        system.debug(accList);
    }
}

anonymous window:
Generate101Error.soql101Error();

Generate SOQL Error 101
  • Bypass this error just by adding @future as below:
public class Generate101Error {
    @future
    public static void soql101Error(){
        List <Account> accList = New List<Account>();
        for(integer i=1 ; i <= 120 ; i++){
            accList = [SELECT Id, Name FROM Account Limit 1];
        }
        system.debug(accList);
    }
}