[SalesForce] trying to get a count of records(records more than 50000 in object) in one object through apex class

Trying to get a count of records(records more than 50000 in object) in one object through apex class(Getting limit Exception). Looking for any alternate solution.

I used database.countQuery()statement, but still I am getting records limit exception.

Any one give me alternate solution to get records count.

My query is dynamic query like:

String s = 'Case';
String soql = 'SELECT COUNT() FROM' + s;
Integer cnt = Database.countQuery(soql);

Best Answer

Why shouldn't you use database.query(query) instead.

AggregateResult results = database.query('SELECT COUNT(id) result FROM someSObject');

System.debug('No of ids are: '+results.get('result')); // Id are always unique

Using database.countQuery() or [SELECT count() FROM someObject]; hits governor limit if records > 50000

If you can use @readonly in you class then that limit will extend to million.

Also try to filter it with some criteria using WHERE clause, field which have no significant of counting if they have some particular value that doesn't matter.

Related Topic