function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion 

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();

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

Too many query rows: 50001
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

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();
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!