Salesforce.com has a limit of 50,000 records which can be queried at one time.  Anytime you have queries with aggregate functions which need to access more than 50,000 records you’ll get the following error:

“System.LimitException: Too many query rows: 50001″

For example let’s say you want to count the number of contacts in your organization:

System.debug('total: ' + [SELECT count() FROM Contact]);

We are just trying to count the number of records, and in a traditional SQL engine such a call would not need to transverse every record in the Contacts table to obtain this count. However, in Salesforce it does…why? Well as one example something like checking sharing settings on records so that different profile users get different number of records.

There are several techniques you can use to get around this problem. My choice however, is to use the REST API. There are other solutions available including using the ReadOnly attribute on a Visual Force page or Creating a Batchable Apex Class, but I find that the REST API solution is the easiest and offers the most flexibility.

The REST API allows for the execution of a query by setting the query string parameter “q” equal to the requested query. Note that you must first MIME encode your SOQL query. The simple example below:


HttpRequest req = new HttpRequest();

req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v30.0/query/?q=SELECT+Id+from+Contact');

req.setMethod('GET');

string auth = 'Bearer '+ userInfo.getsessionId();
req.setHeader('Authorization', auth);

Http http = new Http();

try
{
   HttpResponse res = http.send(req);

   string response = res.getBody();
   string total = response.substring(response.indexOf('totalSize":') + 11, response.indexOf(','));
   system.debug('Total: '+ total);
}
catch( Exception e )
{
   system.debug('Error ' + e.getMessage());
}

You can get more elaborate and create a Class that contains methods for each aggregate function, however, the above code will get your around the 50,000 record limit.

Lastly once you have the code written you’ll need to add an entry to your Organizations remote sites. For example say your production org is on na2 you’ll need to add na2.salesforce.com as a remote site.

[contact-form]