function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rklaassenrklaassen 

Workaround for count() query

I created a page in Visual Force / Apex where I show 5 google graphs based on figures I get from 6 count() queries. 1 of them counts the total contacts under an account, the other 5 count the contacts based on criteria (like passed course = yes). 

This works fine if the account has less then 100 contacts. I now have an account that has 2700 contacts in total and the script totally fails because the execution time > 120 seconds. When I take a look at the debug log, I notice that the count() queries take very much time to execute, the count of total contacts takes 40 (!) seconds. Our customer doesn't accept this, but I can't figure out how to reduce this. 

 

Anyone here has an idea?

SargeSarge

Hi,

 

      Counting business in real-time will surely consume a lot of time as number of record grows. Hence instead of counting number of records in real time, keep the counter fields in parent object and update them using

1) Trigger (every time a contact record is inserted, deleted, undeleted)

2) An Apex class that is scheduled to do something. In your case, counting. The schedule may run every half an hour, an hour or nightly depending on your need.

 

Also you can use Batch Apex Jobs to count contacts (not using count())  using QueryLocator object. They are capable of returning bulk records bypassing governor limits. See Batch Apex Documentation.

 

Hope these methods suits you.