title: LimitException: Too many query rows: 50001 from with count() aggregate function
body: <p>I have a Visualforce page where I'd like to display a count of the number of records in a particular sObject table.</p>
  <p>In the Visualforce page I'd have something fairly simple, like:</p>
  <pre><code>&lt;p&gt;Client Account Count: {!ClientAccountCount}&lt;/p&gt;
  </code></pre>
  <p>Then in the controller:</p>
  <pre><code>// Return the number of clients
  public integer getClientAccountCount() {
      return [Select count() from Account where SomeCustomField__c = 'Client' limit 50000];
  }
  </code></pre>
  <p>I thought with the limit clause in the SOQL I'd be fine as it would only every return a maximum of 50,000. However, in practice I still get this exception in the production org:</p>
  <blockquote>
  <p>09:29:12:179 SOQL_EXECUTE_BEGIN [108]|Aggregations:0|select count() from Account where SomeCustomField__c = 'Client' limit 50000</p>
  <p>09:29:12:331 EXCEPTION_THROWN [108]|System.LimitException: Too many query rows: 50001</p>
  </blockquote>
  <p>Is there a safe way to perform this query that won't result in an exception that I can't catch?</p>
  <p>Oddly, if I try the following as anonymous apex in production it works just fine and returns 50,000.</p>
  <pre><code>integer count = [select count() from Account where SomeCustomField__c = 'Client' limit 50000];
  </code></pre>
  <p>Perhaps the issue is the cumulative number of query rows across all operations that is causing the problem and I need to check the Limits in code before running the query?</p>
  <hr />
  <p>There is a similar post on the Force.com discussion boards - <a href="http://boards.developerforce.com/t5/Apex-Code-Development/Too-many-query-rows-on-COUNT-function/td-p/406473" rel="nofollow noreferrer">Too many query rows on COUNT(*) function</a>. I can't set the VF page to read only to increase the query row limit.</p>