0

I am getting 50001 Soql Error when i am trying to do with the following code:

 private static Integer getNumberOfRecords (String objectName, String whereClause) {
    String soql = ''
            + ' SELECT Count(Id)' 
            + ' FROM ' + objectName + ' ' 
            + whereClause
            ;

     system.debug('getNumberOfRecords123 = ' + soql);       
    AggregateResult results;        
    Map<String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
    objectName = getFieldNameWithPrefix(objectName);
    Schema.SObjectType sobjType = gd.get(objectName); 
    Schema.DescribeSObjectResult describeResult = sobjType.getDescribe();
    if (describeResult.isAccessible()){
        results = Database.query(soql);
    }
    //results = Database.query(soql); 
    system.debug('getNumberOfRecords123 = ' + soql);
    system.debug('getNumberOfRecords = ' + results.get('expr0'));  

    Integer records = Integer.valueOf(results.get('expr0')); 
    return records;                 
}

How can I use a LIMIT clause in this query?

4

You can't use a LIMIT clause with an aggregate query in this way. In fact, if there are more than 50k records, you cannot determine the exact count synchronously. The best you can do is say there are at least 50,000.

However, you can add it to a true count query:

SELECT count() FROM MyObject__c LIMIT 50000

Then you would just return the count directly:

return Database.countQuery(soql);

Which you could merge in using:

+ ' LIMIT 50000'
  • Thanks @Adrian Larson For your Solution, Thanks for helping – user44771 May 30 '17 at 7:38
2

If that is the only query in the transaction:

String soql = ''
        + ' SELECT Count()' 
        + ' FROM ' + objectName + ' ' 
        + whereClause
        + ' limit 50000'
        ;

Then if the number returned is 50,000, you can inform the user that there are at least 50,000 records but cannot say how many more. (Below 50,000 you can give them the exact number.)

If you execute this from a page that doesn't need to update anything, then you can set readOnly="true" on the apex:page and increase the number to 1 million.

  • if use LIMIT, I am getting this type of Error: Non-grouped query that uses overall aggregate functions cannot also use LIMIT – user44771 May 29 '17 at 16:23
  • @SFDCDeveloper Remove the Id from the Count. I added that to the answer. – Keith C May 29 '17 at 16:27
0

I Have tried like this.

 Integer intCount = 0;

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

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

Its Working and now i am getting Full count of Records.

Thanks.