[SalesForce] Best way to do a count() from a custom object having more than 1 million records

I have a custom report which i need to build on visual force page which is displayed on a force.com site. I have to display count() of records on a custom object which has more than 500k records. I am using a soql query like this
SELECT COUNT() FROM ACS_USER__c WHERE (CreatedDate >= :fromDate AND CreatedDate <= :toDate)];
This query is throwing a governor limit of more than 150,000 records limit. What will be the best way to do this to avoid the governor limit?

Best Answer

I think you cannot get the complete count using a SOQL, not 100% sure. Initially I thought you could use a @readOnly annotated method and then get the count but then i think that cannot be done as the you will be executing the query from the context of a VF page. But I can think there are ways of doing this, As of now I can think of 2 methods(I am sure there will be easier way of doing this):

1.) You can make a http request using the REST API. Before using this code make sure you add the salesforce url in the remote site setting. The response you get contains contains a atribute called "totalSize", which gives you the count of number of rows returned by the query (which is mentioned in the REST URL).You can run the below code in the developer console to check. to get the use the below code:

    HttpRequest req = new HttpRequest();
 req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v20.0/query/?q=SELECT+name+from+Account');
 req.setMethod('GET');

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

 Http http = new Http();
 HTTPResponse res = http.send(req);
 string response = res.getBody();
 string totalCount = response.substring(response.indexOf('totalSize":')+11, response.indexOf(','));
system.debug('get the total count '+ totalCount);

2.) As you mentioned you are using a VF page, you can do the rest call in the VF page itself which is easier way, using jquery:

$.ajax({
url : "https://yourinstance/services/data/v20.0/query/?q=SELECT+name+from+Account",
headers : {"Authorization": "Bearer "+ AddSessionId}, //make sure you add the sessionId
contentType : "application/json"
}).done(function(response){
    console.log('The count is '+ response.totalSize);

});
Related Topic