Platform
Too many query rows: 50001 in Apex
Reduce retrieved rows or use a suitable batch boundary; distinguish row limits from query count and memory use.
A query can be bulkified and still retrieve too many records. One large result set can exhaust the transaction’s row budget.
The ordinary SOQL row ceiling is 50,000, as documented in the governor reference. Query count and row count are separate budgets. A SOQL for loop changes how results are processed in memory; it doesn’t generally remove the row ceiling.
Decide what the caller needs
If the caller needs a total, evaluate an aggregate query rather than retrieving each record solely to count or sum it. If the caller needs a page of results, design explicit pagination and a stable ordering. If the task must process every matching record, use a background mechanism suited to that volume.
Adding an arbitrary LIMIT makes an exception disappear by dropping work. That is only correct when the business contract explicitly permits a limited result, such as a preview. The response should then distinguish a preview from the complete set.
Inspect relationship subqueries as well as top-level queries. A modest number of parent records can bring back many children. Record the shape of the failing data so that your regression test exercises the same fan-out.
Measure the complete transaction
The Limits class exposes row counters:
System.debug(LoggingLevel.WARN,
'Query rows: ' + Limits.getQueryRows() +
'/' + Limits.getLimitQueryRows());
Measure around the suspicious selector, then inspect other selectors called by the save. Repeatedly retrieving the same large set is still repeated work. Reducing fields can improve memory usage, but it doesn’t reduce the number of rows returned.
Avoid assuming that a count query, aggregate query and ordinary record query have interchangeable limit behavior. Check the specific query shape and returned groups against the current reference, then measure the implementation.
Use the batch query locator deliberately
Batch Apex documents a special allowance for the QueryLocator returned by start, supporting large record scopes. That exception does not give ordinary queries inside execute unlimited rows.
Choose an execute scope that leaves room for related data, writes and callouts. Batch scopes can commit independently, so provide a completion report that distinguishes processed records from failures. The job reaching its end does not prove every intended update succeeded.
Test a scope containing a parent with many related records and a record that fails validation. Also test the filter: processing the wrong population successfully is still a failed implementation.
For an interactive page, prefer a bounded result with an explicit next-page mechanism. For a complete back-office job, prefer an observable background process. The distinction should come from the caller’s needs, not from whichever syntax avoids the exception first.