0

Problem: I am using SOQL query to retrieve more than 50000 records inside start method and passing those records to query locator. I am getting this error :Too many query rows: 50001 in batch class.

Batch

global Database.QueryLocator start(Database.BatchableContext BC) {

        String oppQuery = 'SELECT Id FROM Opportunity WHERE StageName NOT in (\'Duplicate\',\'Closed Lost\',\'Cancelled\',\'Prospect\',\'Active - Low Probability\',\'Active - Med. Probability\') ';
        List<Opportunity> Opp = new List<Opportunity>(); 
        System.debug('oppQuery '+oppQuery);     
        Opp = database.query(oppQuery);


        List<Id> oppIds = new List<Id>();
        for(Opportunity o : Opp)
        {
           oppIds.add(o.ID);
        }


        String query = 'SELECT id FROM OpportunityLineItem WHERE (NOT(Product2.Name like \'%ECO%\')) AND  Primary__c = true  AND OpportunityId IN: oppIds';     
        System.debug('query query '+query );    
        return Database.getQueryLocator(query);

    }

Error Line:

String oppQuery = 'SELECT Id FROM Opportunity WHERE StageName NOT in (\'Duplicate\',\'Closed Lost\',\'Cancelled\',\'Prospect\',\'Active - Low Probability\',\'Active - Med. Probability\') ';

How can I fix this error?

1 Answer 1

2

You can Optimize your second query to include the condition and using that you don't need 2 query.

Set<String> strSet =new Set<String>()
strSet.add('Duplicate');
strSet.add('Closed Lost');
strSet.add('Cancelled');
strSet.add('Prospect');
strSet.add('Active - Low Probability');
strSet.add('Active - Med. Probability');
String query = 'SELECT id FROM OpportunityLineItem WHERE (NOT(Product2.Name like \'%ECO%\')) AND  Primary__c = true  AND Opportunity.stageName NOT IN: strSet'; 

Now you can query records without any issue. You don't need 2 query anymore.

2
  • This doesn't seem like it calls for a dynamic query, wouldn't the [SELECT...] style be safer and more maintainable here? Dec 9, 2017 at 3:32
  • @ca_peterson yes it surely will but I don't want to confuse her as in first query she is using dynamic SOQL as well. Dec 9, 2017 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.