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
Luciano Castro 2018Luciano Castro 2018 

"Too many query rows: 500001" on list?

How can I add a filter to this code to prevent this error message?

public with sharing class ApexClassHomeWork 
{
    public List<Account> accs {get; set;}
    
    // retrieves the list of accounts backing the page
    public ApexClassHomeWork()
    {
        accs=[select id, Name, BillingStreet, BillingCity, BillingPostalCode FROM Account  WHERE Name LIKE 'Test%' LIMIT 10];
    }
    
    public void createContact(Id acctId)
    {
       list<contact>contList = newlist<contact>();   
       for(Integer i=0; i<500; i++)
        {
            Contact c = new Contact(AccountId=acctId, "last name");
            contList.add(c);
        }
        if(contList.size()>0)
             update contList;
    }
}
Raj VakatiRaj Vakati
The total number of records retrieved by SOQL queries = 50,000 in Single Transaction in Salesforce. To Solve it, User 
  • Use Proper where clause, Instead of like use == 
  • Use Batch Apex, in which the 50k limit counts per batch execution
  • Set  limit of 50000  
  • Use Read-only mode on Page if you want to just display 
  • Use may use Aggregate  Query to avoid the data processing 

What you can do it show the proper error message is, create an apex exception class and though it from try and catch 
 
 
Luciano Castro 2018Luciano Castro 2018
Hi Raj

Would you say the updated line should be 

accs=[select id, Name, BillingStreet, BillingCity, BillingPostalCode FROM Account  WHERE Name == 'Test%' LIMIT 10]

Using == instead of LIKE?
Luciano Castro 2018Luciano Castro 2018
The LIMIT shows 10, do I have to change to 50000?