+ Start a Discussion
sudhirn@merunetworks.comsudhirn@merunetworks.com 

Load Query Count into a variable

Hi  Experts,

 Below code is working fine have no problem because of this too many queries am gettin 50001 issue when migrated to production

  Is there any alternative way to load the query count to the variable please suggest me
     
String query = 'SELECT Id, Name, OwnerId, Owner.Name, NextStep, StageName, Total_List_Price_Amount__c, ForecastCategoryName, '+
                        'CloseDate, Amount,Formula_Amount__c,(Select Id,Name,Status__c from SPR__r ORDER BY CreatedDate DESC LIMIT 1) '+
                       'FROM '+
                        'Opportunity '+
                       'WHERE '+
                        'Id != null';


  List<Id> listOppIds = new List<Id>(); 
        //List<Opportunity> CountOppRecords = Database.query(query);
        total_size = CountOppRecords.size();

Thanks
Sudhir
Lokesh__PareekLokesh__Pareek
String QueryString = 'SELECT count() FROM Opportunity';
Integer i = Database.countQuery(QueryString);
sudhirn@merunetworks.comsudhirn@merunetworks.com
Thanks Lokesh for your reply I am getting below error please suggest how to fix this issue.  

Too many query rows: 50001
Lokesh__PareekLokesh__Pareek
Depending on the scenario you can use one of following approach :

1) Setting Read-Only Mode for an Entire Page / Setting Read-Only Mode for Controller Methods
    https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_readonly_context_pagelevel.htm
    https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_readonly_context_methodlevel.htm

2) Batch class
    
    
public class CountOpp implements Database.Batchable<sObject>, Database.Stateful {
    Integer total = 0;
     
    public Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator('select Id from Opportunity');
    }
    
    public void execute(
            Database.BatchableContext BC, 
            List<sObject> scope){
        total += scope.size();
    }
 
    public void finish(Database.BatchableContext BC){
        System.debug('total: ' + total);
    }
}
//Execute batch
Database.executeBatch(new CountOpp(), 2000);

3) Using Rest API
 
HttpRequest req = new HttpRequest();
req.setEndpoint('https://'+URL.getSalesforceBaseUrl().getHost()+'/services/data/v20.0/query/?q=SELECT+Id+from+Opportunity');
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);

Hope it helps!