I have a batch executed : 1 out 4200 is failing with : inline query has too many rows for direct assignment,use FOR loop

My code in the exec function:

    List<String> personAccountsIDs = getPersonAccountsIDs(accountList);

    List<Contact> contactList = [Select ID,Name
                                (Select Name,ID,Brand__c,Customer_Type__c from Profiles__r),
                                (Select ID,Brand__c from Purchases__r)
                                from Contact
                                where AccountID in : personAccountsIDs];

    for(Contact c : contactList){

            Set<String> brandPurchased = new Set<String>();
            for(Purchase__c p : c.Purchases__r){
                if(p.Brand__c !=null)

when I see my log , the error is on the query, however I followed the instructions of Salesforce regarding the loop, and for so records, I do have more that 200 purchases, what can I do to solve the issue for the 1 failing process in the batch?


Rather than performing the query into a local variable the query must be embedded in the for statement itself for this optimization to work. (That said, I don't know if this will resolve the issue in the context of a batch execution.)

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