i need to count total number of records in an sObject which can have around one million records. Will the code below work ? If no, how can this be done ? I dont need to use this in a vf page.
I will be using this COUNT() SOQL Query in a batch class which is scheduled to run at specific time.
AggregateResult results = database.query('SELECT COUNT(id) result FROM someSObject'); System.debug('No of ids are: '+results.get('result'));
Answer
(comical but unsupported)
You can wedge your aggregate query inside of a FOR
loop. This expands the ceiling beyond the 50,000 limit. Ultimately undocumented behavior, that probably shouldn’t be relied upon.
Integer total = 0;
for (AggregateResult result : [
SELECT COUNT(Id)
FROM SomeObject__c
]) total += (Integer)result.get('expr0');
System.assert(false, total); //big number
Ratan confirms that even a GROUP BY
clause is not needed in the query. Neat!
Attribution
Source : Link , Question Author : Walker , Answer Author : Matt and Neil