[SalesForce] How to resolve the LimitException

for(PricebookEntry pbe:[Select product2Id from PricebookEntry where PriceBook2Id = :pbId]){
            productIds.add(pbe.product2Id);
        }

I am getting the following exception.

System.LimitException: Too many query rows: 50001
An unexpected error has occurred. Your solution provider has been notified. (Database).

It should process the records in batch why am i getting the above error?

Best Answer

Even if you are executing in batch please note that the execute class still holds all the governor limits .Only the Object which is queried in Database.QueryLocator gets chunked while processing .The query in constructor or the start method or your scope is prevented from query limit .If you have 50000 pricebook entry for PriceBook then query will fail.