[SalesForce] REQUEST_RUNNING_TOO_LONG,query Timeout in Batch Apex

The batch is Failing since couple of weeks and throwing error:

First error: [REQUEST_RUNNING_TOO_LONG] Your request was running for
too long, and has been stopped

Mostly it seems to happen due to very long query,Any suggestion how it could be resolved?

query

 select id, BAN__r.Name, BAN__r.BAN_Status__c,
 BAN__r.Status_last_date__c, ClosedDate from case where
 (BAN__r.BAN_Status__c ='C' and BAN__r.Status_last_date__c <
 2015-06-23) or(BAN__c = null and ClosedDate <
 2015-06-23T08:56:45.000Z)or  (RecordTypeID = '01220000000Q2UR' and
 Type = 'Account Administration' and  Case_Sub_Type_1__c = 'Direct
 Debit Request'  and CreatedDate < 2017-04-21T08:56:45.000Z)

Best Answer

You should seperate your query in two queries.

The first sould query your BAN__c object:

Map<Id, Ban__c> bans = new Map<Id, Ban__c>([SELECT Id FROM Ban__c WHERE BAN_Status__c = 'C' AND Status_last_date__c < 2015-06-23]);

The second would use the results of the first in its first condition:

select id, BAN__r.Name, BAN__r.BAN_Status__c, BAN__r.Status_last_date__c, ClosedDate from case where (BAN__c IN :bans.keySet()) or(BAN__c = null and ClosedDate < 2015-06-23T08:56:45.000Z)or  (RecordTypeID = '01220000000Q2UR' and Type = 'Account Administration' and  Case_Sub_Type_1__c = 'Direct Debit Request'  and CreatedDate < 2017-04-21T08:56:45.000Z)