I have a batch class to update case object. When i am running this job, getting an error: Too many SOQL queries.

Can some one help me to write the 'query on feeditem' out side of the for loop in EXECUTE method.

Here is my code.

global class BatchtoUpdateBusinessDays implements Database.Batchable { Public final String Query;

    global BatchtoUpdateBusinessDays() {
        query = 'SELECT Id,Status,No_of_Days_Case_Untchd_Business_Days__c FROM Case WHERE Status != \'Closed\' or Status != \'Duplicate\' or Status != \'Deleted\'';

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

       return Database.getQueryLocator(query);


global void execute(Database.BatchableContext BC, List<Case> scope) {
    list<businesshours> bh  = new List<businesshours>([select id,Name from businesshours where Name = 'Working Days']);

 for(Case c : scope)

     String BusinessHours_Id = bh[0].Id;
     list<Feeditem> FIlist = new list<Feeditem> ([Select Id, CreatedDate from Feeditem where parentId = :c.Id]);
     Long  Mins_since_lastTouched = BusinessHours.diff (BusinessHours_Id, FIlist[0].CreatedDate, System.Now()) / 1000 / 60;
     System.debug('<<<<>>>>'+ Mins_since_lastTouched );
     c.No_of_Days_Case_Untchd_Business_Days__c = Mins_since_lastTouched / 24 / 60;
     System.debug('<<<<>>>>'+ c.No_of_Days_Case_Untchd_Business_Days__c );
 update scope;


global void finish(Database.BatchableContext BC) {

} }

  • Avoid SOQL Queries or DML statements inside FOR Loops Nov 9, 2016 at 12:11
  • Can you please help out here, to write the logic outside of for loop. Since i am facing errors when accessing the values of the query.
    – venky
    Nov 9, 2016 at 12:13
  • You should really write this functionality as a trigger on FeedItem.
    – Adrian Larson
    Nov 9, 2016 at 12:27

1 Answer 1


Here is sample code to take out of soql from for loop.

//Case Id List
List<Id> caseIdList = new List<Id>();
for(Case temp : scope) {
//Feed Item List
List<Feeditem> feedList = [select id,Parentid,....from FeedItem Where Parentid in :caseIdList];
Map<Id,FeedItem> caseIdFeedMap = new Map<Id,FeedItem>();
for(FeedItem item : feedList) {

for(Case temp : scope) {
//your logic
if(caseIdFeedMap.containsKey(temp.id)) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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