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

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

System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop Salesforce Exception is thrown when the sub-query returns too many rows.

In order to avoid System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop, make sure the sub query is limited or filtered.

Sample Incorrect Code:

for ( 
    Account acc : [ 
        SELECT Id, ( SELECT Id FROM Contacts ) 
        FROM Account 
    ] 
) {
    
    if ( acc.Contacts.size() > 0 ) {
        
        System.debug( 
            'Contacts size is ' + acc.Contacts.size()
        );
        
    }
    
}

Correct Code:

List < Account > lstAcct = [ 
    SELECT Id, ( SELECT Id FROM Contacts ) FROM Account 
];

for ( Account acc : lstAcct ) {
    
    if ( acc.Contacts.size() > 0 ) {
        
        System.debug( 
            'Contacts size is ' + acc.Contacts.size()
        );
        
    }
    
}

Leave a Reply