How to Resolve Too Many Query Rows Error in Salesforce Apex

April 03, 2026
263 Views
How to Resolve Too Many Query Rows Error in Salesforce Apex
Summarize this blog post with:

Being a Salesforce developer , I hope you must have come across the “Too many query rows: 50001” error in Salesforce while working with Apex ,Test class , Flow or handling large data sets. It’s one of those common governor limit errors that every developer runs into at some point mostly in full copy sandbox and production.

Let’s break down in this Triggerhours article what this error actually means, why Salesforce enforces it, and how you can fix and prevent it in your code going forward.

What is the “Too many query rows: 50001” Error?

This System.LimitException means the number of rows returned by all SOQL queries in one Apex transaction exceeds some Salesforce platform limits.Salesforce enforces this limit to provide equitable resource distribution in its multitenant architecture. Fetching too many records uses a lot of server memory and processing power, which might degrade performance of the server for other users that are tied to the same resources.

The specific governor limit is:

  • Total number of records retrieved by SOQL queries: 50,000
When your transaction’s cumulative record count from all SOQL queries hits 50,001 or more, Salesforce immediately terminates the transaction and throws this exception.

What Causes the “Too many query rows” Error?

This error is commonly caused by an inefficient SOQL queries that return excessive data to process or performs operations on large amount of data in a single synchronous transaction.
Cause 1: Non-Selective SOQL Queries

The most common cause is writing SOQL queries without sufficiently selective WHERE clauses , LIMIT, especially when querying objects that tend to have a large number of records . So we should always make our Make SOQL query selective

Example:
// ERROR : Querying all Task records without any filter
// In an org with over 50,000 tasks, this will fail.

List allTasks = [SELECT Id, Subject FROM Task];
Cause 2: Querying Large Datasets Synchronously
Trying to work with too many records in one-go in a synchronous context (trigger, button click handler, Visualforce controller action) usually results in this error.
Example:
// Trying to process all Accounts in a trigger handler
// If the org has > 50,000 Accounts, this query fails immediately.

List allAccounts = [SELECT Id, Name, AnnualRevenue FROM Account];
for (Account acc : allAccounts) {
    // Some logic here...
}
Cause 3: Accumulating Rows Across Multiple Queries
Always remember, the limit applies to the total number of rows retrieved across all SOQL queries in the transaction. Even if individual queries retrieve fewer than 50,000 rows, their cumulative total can exceed the limit.
Example:
// Query 1 retrieves 30,000 records

List contacts = [SELECT Id FROM Contact WHERE Account.Type = 'Customer'];
 
// Query 2 retrieves 25,000 records

List leads = [SELECT Id FROM Lead WHERE Status = 'Open'];
// Total rows = 55,000. The second query will likely cause the exception.

How to Resolve the “Too many query rows” Error?

Correcting this error is a matter of tweaking your data fetching strategy. The idea is to either fetch less records, or handle large amounts of records in a way that the platform limitations are respected.
Solution 1: Use Selective WHERE Clauses

This is the most crucial fix. Always filter your SOQL queries to retrieve only the records you actually need. So we should always make our Make SOQL query selective by following Salesforce help article. Filter on Indexed Fields: Make use of indexed fields in the WHERE clause contains (for example, Id, Name, OwnerId, CreatedDate, External IDs, and indexed custom fields). This makes the database to locate the relevant records with much higher speed and efficiency.

Be Specific: Make your conditions as specific as possible to narrow down the result set.

You can also reach out to Salesforce support to get your custom field indexed to Improve Performance of SOQL Queries

Inefficient Example:

List accounts = [SELECT Id FROM Account WHERE Name LIKE 'A%']; // Still potentially large
Optimized Example:
// Filter by a specific record type AND an indexed field (OwnerId)
Id specificRecordTypeId = '012.....';
 
List accounts = [
    SELECT Id
    FROM Account
    WHERE RecordTypeId = :specificRecordTypeId
    AND OwnerId = :UserInfo.getUserId()
]; // Much more selective

Solution 2: Use LIMIT Clauses
If you only need a subset of records or want to explicitly cap the number of records retrieved, use the LIMIT clause. This is often useful for displaying preview data or when you only need some examples, not all records.
Example:
// Retrieve only the 1000 most recent Tasks, not all of them.

List recentTasks = [
    SELECT Id, Subject
    FROM Task
    ORDER BY CreatedDate DESC
    LIMIT 1000
];
Solution 3: Process Large Datasets Asynchronously with Batch Apex
For scenarios that do really need over 50,000 records processed (such as nightly data updates, mass calculations), synchronous Apex is not the tool. You have to use Batch Apex.
Batch Apex is optimized to handle large volumes of data by dividing the job into manageable chunks (batches) and each batch has its own set of governor limits which also includes the 50,000 row s query limit. The start method’s Database. QueryLocator can query millions of records and you won’t hit the limit at that phase.
Example (Batch Apex Structure):

global class ProcessLargeAccountDataBatch implements Database.Batchable {
 
    global Database.QueryLocator start(Database.BatchableContext BC) {
        // This QueryLocator can handle millions of records without hitting the 50k limit here.
        return Database.getQueryLocator('SELECT Id, Name, AnnualRevenue FROM Account WHERE Needs_Processing__c = true');
    }
 
    global void execute(Database.BatchableContext BC, List scope) {
        // 'scope' contains a batch of records (default 200).
        // Any queries INSIDE execute must respect the 50k limit for THIS batch transaction.
        for (Account acc : scope) {
            // Process each account...
        }
        // update scope; // DML on the batch
    }
 
    global void finish(Database.BatchableContext BC) {
        // Optional: Send completion email, etc.
    }
}
Solution 4: Optimize Overall Logic
Sometimes, you can restructure your code to avoid querying large numbers of records altogether. Can you achieve the goal by querying fewer, more targeted records? Can you use Aggregate SOQL queries (COUNT(), SUM()) to get summarized data instead of individual rows?

A Simple Demo: From Bug to Fix

The Buggy Code (Causes the Error)
// Open Developer Console -> Debug -> Open Execute Anonymous Window
// Run this code. It will likely fail in an higer org with lots of activity records.
Example:

try {
    // Attempting to query ALL Task records - very likely > 50,000
    List allTasks = [SELECT Id FROM Task];
    System.debug('Total tasks found: ' + allTasks.size());
 
} catch (System.LimitException e) {
    System.debug('Caught expected error: ' + e.getMessage());
    // You should see the "Too many query rows: 50001" error here.
}
The Fixed Code (Using LIMIT and WHERE)
// Now run this fixed version. It should succeed.
Example:

try {
    // The Fix: Add a selective WHERE clause and a LIMIT
    Date oneMonthAgo = System.today().addMonths(-1);
 
    List recentTasks = [
        SELECT Id, Subject
        FROM Task
        WHERE CreatedDate >= :oneMonthAgo
        AND OwnerId = :UserInfo.getUserId()
        LIMIT 1000
    ];
 
    System.debug('Found ' + recentTasks.size() + ' recent tasks for the current user.');
 
} catch (System.LimitException e) {
    // This block should ideally not be hit now
    System.debug('Unexpected error: ' + e.getMessage());
}

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Written by

Aditya Singh

TriggerHours is a platform built on a simple idea: "The best way to grow is to learn together". We request seasoned professionals from across the globe to share their hard-won expertise, giving you the in-depth tutorials and practical insights needed to accelerate your journey. Our mission is to empower you to solve complex challenges and become an invaluable member of the Ohana.

Get the latest tips, news, updates, advice, inspiration, and more….

Contributor of the month
contributor
Mykyta Lovygin

SFCC Developer | SFCC Technical Architect | Salesforce Consultant | Salesforce Developer | Salesforce Architect |

...
Categories
...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...

Leave a Reply

Your email address will not be published. Required fields are marked *