5

Following query won't work if number of records is more than 50,000.

Integer c = [SELECT COUNT() FROM MyObj__C];

Is there a workaround to do calculation anyway?

Samuel De Rycke
  • 9,550
  • 8
  • 45
  • 73
ClassCastException
  • 2,182
  • 1
  • 21
  • 43

4 Answers4

6

http://www.salesforce.com/us/developer/docs/pages/index_Left.htm#StartTopic=Content/pages_controller_readonly_context.htm

Set the context to read Only .Read only on page will allow you to query for million records atleast

<apex:page controller="SummaryStatsController" readOnly="true">
   <p>Here is a statistic: {!veryLargeSummaryStat}</p>
</apex:page>

Controller code

public class SummaryStatsController {
public Integer getVeryLargeSummaryStat() {
    Integer closedOpportunityStats = 
        [SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true];
    return closedOpportunityStats;
}
}
Mohith Shrivastava
  • 91,131
  • 18
  • 158
  • 209
  • If i dont have an apex page, can i add @Readonly annotation to the method in class and call this class method from a class which implements batchable and does some delete dml operations. I need record count in a batch class which does dml delete. – Walker Dec 10 '15 at 11:25
2

With the Summer '18 Release there was a new feature for this:

Basically, the COUNT() no longer contributes towards the query row limit (typically 50,000 records). Instead in counts once towards that limit. There is some additional consideration when using GROUP BY, but generally you can count a far greater number of records now.

Daniel Ballinger
  • 102,288
  • 39
  • 270
  • 594
1

I think, You have to write a batch class for this . In execute method, You can have static method and increase the count based on how many time methods get called. Please put Database.stateful to maintain the value of the variable. Thanks.

amidstCloud
  • 2,827
  • 4
  • 35
  • 57
1

Use the countQuery it does not count against that limit

I know that here is 7 years old but nobody really answered it without using a class and VF

sample works in dev-console and returns for me USER_DEBUG [1]|DEBUG|184880 system.debug(Database.countQuery('select count() from Asset'));

Moggy
  • 87
  • 5