4

I would like to know how many records are there for a given Object. I have written code (SOQL) which can show record count for <= 50000 records but I have 2 Million records then how can I get an exact count.

FYI: I also used a read-only attribute in a VF page, but it can read up to 1 Million records.

4

1. Use Aggregate query

public class Test_Aggregate{
        public static void TestAgg() {
            Integer intCount = 0;

            for(AggregateResult result :[SELECT COUNT(Id) intVal FROM Custom_Object__c])
            {
                intCount+=(Integer)result.get('intVal');
            }

            System.debug('No of records are: '+intCount);
        }
    }

2. Use Readonly notation

@ReadOnly only work with JS remoting. If you direct call the method using class instance then it wouldn't work

Here is the example(IN this example I have 97000 Task records.)

<apex:page controller="TestVFpage">

    <div id="totalAccounts"></div> 
                <script>
                Visualforce.remoting.Manager.invokeAction(
                    '{!$RemoteAction.TestVFpage.getTask}',
                        function(result){
                            alert('Total Records: '+result.length);
                        }

                    );
                </script>
</apex:page>

Controller

public class TestVFpage {
    @RemoteAction
    @readOnly
    public static list<Task> getTask(){
        return [SELECT Id FROM Task];
    }
}

alert message enter image description here

3. Use rest api using jquery.

<apex:page>
   <input name="getList" class="btn" value="Get Account list" type="button" onclick="getSobjectList()" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
   <script>
      var $j = jQuery.noConflict();
      var sessionId = '{!$Api.Session_ID}';
      function getSobjectList() {
      $j.ajax({
      type: "GET",
      url: "/services/data/v35.0/query?q="+''+"{!URLENCODE('SELECT count(Id) totalTask FROM Task')}",
      headers: {"Authorization" : "OAuth " + sessionId},
      crossDomain : true,
      dataType: 'application/json',
      success: function (responseData) {
      console.log(responseData);
      },
      error: function (request, status, error) {
      console.log(request.responseText);
      }
      });
      }
   </script>
</apex:page>

check browser console

enter image description here

|improve this answer|||||
  • 1
    Thank you @Ratan, your first approach solved my problem but the rest 2 failed for records >= 1000000 – Mahadev Wagalgave Jul 5 '16 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.