System.QueryException: Aggregate query has too many rows for direct assignment: meaning and how to fix it

SOQL and queries Checked against the official docs on Source: SOAP API Developer Guide: Core Data Types, StatusCode

Quick answer

System.QueryException: Aggregate query has too many rows for direct assignment: A query that returns more rows than direct assignment to a list or variable allows was assigned directly. Start with: Use a SOQL for loop to process the rows in chunks.

Typical message: System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop

Cause

A query that returns more rows than direct assignment to a list or variable allows was assigned directly.

How to fix System.QueryException: Aggregate query has too many rows for direct assignment

  1. Use a SOQL for loop to process the rows in chunks.
  2. Add filters or LIMIT to return fewer rows.
for (Account a : [SELECT Id FROM Account]) {
    // process one record at a time
}

Have a different message? Paste it into the error decoder, which matches it against 45 common Salesforce errors in your browser.

Frequently asked questions

What does System.QueryException: Aggregate query has too many rows for direct assignment mean in Salesforce?

A query that returns more rows than direct assignment to a list or variable allows was assigned directly.

How do I fix System.QueryException: Aggregate query has too many rows for direct assignment?

1. Use a SOQL for loop to process the rows in chunks. 2. Add filters or LIMIT to return fewer rows.

More SOQL and queries errors

SFDX Talk is unofficial documentation. It is not affiliated with, endorsed by, or sponsored by Salesforce, Inc. Message text varies slightly by release and context, so confirm against the official page before relying on it.