System.LimitException: Too many query rows: 50001

PROBLEM

This error occurs when you are trying to return more than 50000 records from the SOQL query. In order to resolve the issue either you will have to limit the number of records returned from the SOQL or you will have to process them in the chunks.

Example:

[SELECT Id FROM Lead] // no filter

WORKAROUD

  • Limit the query by using LIMIT keyword.
  • Add filter to process only required data. Must use WHERE clause.
  • Use Batch class if number of rows unavoidable.