Activity Forums Salesforce® Discussions How to query records from sObject for 50000+ records?

  • Ajit

    Member
    April 28, 2016 at 11:52 am
  • Gourav

    Member
    April 29, 2016 at 9:24 am

    There two more methods to query data more then 50000

    Method 1: Use Visualforce page with readOnly attribute set to true
    Controller class:

    public class StatsController {
    public Integer numberOfContacts {
    get {
    if (numberOfContacts == null) {
    numberOfContacts = [select count() from Contact];
    }
    return numberOfContacts;
    }
    private set;
    }
    }
    Visualforce page:

    <apex:page controller="StatsController" readOnly="true">
    <p>Number of Contacts: {!numberOfContacts}</p>
    </apex:page>

    Method 2: Make a http request using the REST API
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v20.0/query/?q=SELECT+Id+from+Contact');
    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 total = response.substring(response.indexOf('totalSize":') + 11, response.indexOf(','));
    system.debug('Total: '+ total);

  • shafali

    Member
    April 29, 2016 at 10:15 am

    Thanks

  • Parul

    Member
    September 12, 2018 at 4:42 pm

    Hi,

    You can use Batchable class:

    public class ContactBatchable implements Database.Batchable<sObject>, Database.Stateful {
    Integer total = 0;

    public Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator('select Id from Contact');
    }

    public void execute(
    Database.BatchableContext BC,
    List<sObject> scope){
    total += scope.size();
    }

    public void finish(Database.BatchableContext BC){
    System.debug('total: ' + total);
    }
    }

    And then execute the following statement in developer console:

    Database.executeBatch(new ContactBatchable(), 2000);

    Thanks.

  • shariq

    Member
    September 14, 2018 at 2:05 am

    Hi,

    You can try this -

    controller - 

    public class StatsController {
        public Integer numberOfContacts {
            get {
                if (numberOfContacts == null) {
                    numberOfContacts = [select count() from Contact];
                }
                return numberOfContacts;
            }
            private set;
        }
    }

    vf page -

    <apex:page controller="StatsController" readOnly="true">
    <p>Number of Contacts: {!numberOfContacts}</p>
    </apex:page>

    Hope this helps.

     

Log In to reply.

Popular Salesforce Blogs