Skip to main content
added 576 characters in body
Source Link
sfdcfox
  • 501.7k
  • 21
  • 473
  • 828

It doesn't matter when you break the loop. IfEdit: Actually, the query returns"Rows" line will show one more than 50,000 rows, or when the sum of all queries in aremaining limit available for the current transaction have exceeded 50,000 rows, you'll getbut the exception. Ifactual value counted against you want to make surewill be 200 more than when you don't getbreak.

Here's demonstration code:

Integer counter = 0;
for(Account[] records: [SELECT Id FROM Account]) {
    counter += records.size();
    if(counter>=20000) {
        break;
    }
}
counter = 0;
for(Account[] records: [SELECT Id FROM Account]) {
    counter += records.size();
    if(counter>=20000) {
        break;
    }
}

Shuffling through the exceptiondebug logs, you must useI note that:

10:58:41:200 SOQL_EXECUTE_END [2]|Rows:50001
10:58:45:389 SOQL_EXECUTE_END [9]|Rows:29801

However, when I look at the LIMIT keyword. All rows returned incumulative usage section, I see that:

10:58:38:000 LIMIT_USAGE_FOR_NS   Number of query rows: 40400 out of 50000 ******* CLOSE TO LIMIT

I actually wasn't aware that this was a query count against youfeature, even if you never examine themso it's good to know.

It doesn't matter when you break the loop. If the query returns more than 50,000 rows, or when the sum of all queries in a transaction have exceeded 50,000 rows, you'll get the exception. If you want to make sure you don't get the exception, you must use the LIMIT keyword. All rows returned in a query count against you, even if you never examine them.

Edit: Actually, the "Rows" line will show one more than the remaining limit available for the current transaction, but the actual value counted against you will be 200 more than when you break.

Here's demonstration code:

Integer counter = 0;
for(Account[] records: [SELECT Id FROM Account]) {
    counter += records.size();
    if(counter>=20000) {
        break;
    }
}
counter = 0;
for(Account[] records: [SELECT Id FROM Account]) {
    counter += records.size();
    if(counter>=20000) {
        break;
    }
}

Shuffling through the debug logs, I note that:

10:58:41:200 SOQL_EXECUTE_END [2]|Rows:50001
10:58:45:389 SOQL_EXECUTE_END [9]|Rows:29801

However, when I look at the cumulative usage section, I see that:

10:58:38:000 LIMIT_USAGE_FOR_NS   Number of query rows: 40400 out of 50000 ******* CLOSE TO LIMIT

I actually wasn't aware that this was a feature, so it's good to know.

Source Link
sfdcfox
  • 501.7k
  • 21
  • 473
  • 828

It doesn't matter when you break the loop. If the query returns more than 50,000 rows, or when the sum of all queries in a transaction have exceeded 50,000 rows, you'll get the exception. If you want to make sure you don't get the exception, you must use the LIMIT keyword. All rows returned in a query count against you, even if you never examine them.