Problem:
You use the 10000 record limit on your queries but they still could fail since you might return 5000 in one and 6000 in the next leading to greater than 10000 records returned. Or potentially more annoying… running into the different limits at play when you are in a test method.
Solution:
Use my rapidly growing Limit Utilities class:
public class LimitsUtility
{
static final Integer PERCENT_PER_QUERY = 65;
public Integer rowsAvailable()
{
Integer rowLimit = Math.round( ( Limits.getLimitQueryRows() - Limits.getQueryRows() ) * ( PERCENT_PER_QUERY / 100.00 ) );
if (rowLimit < 15)
rowLimit = 1;
return rowLimit;
}
}
This function simply takes the total limit and subtracts the available rows, then only queries a certain percentage of the available rows (in this case, 65%).
Use as follows:
List<SObject> sos = [select id from MySObject__c limit = :LimitsUtility.rowsAvailable() ];
I’ve also created a little spreadsheet to show how fast you will burn down the queries at various percentages (assuming you are hitting a full record set).
Note that things won’t be quite this bad if you use my method, since it will drop the limit to 1 if you go below 15 available rows, giving you a little bit of an extra lifeline before you hit the limit. This code is now also available on Snipplr.


Leave a comment
Comments feed for this article