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
moverdorfmoverdorf 

How To Get The Record Count Of SOQL query into a variable...

Hi, I want to return the record count of a dynamic SOQL query, (checkVal is passed in so don't worry about that):

 

Public List<sObject> lstObj;

Public Integer totRecsToProcess;


mystr  = '[select count() from payout__ImportStaging__c where payout__BD_Id__c = \'' + String.escapeSingleQuotes(checkVal) ;

 lstObj = Database.query(mystr);

 

I want to set totRecsToProcess equal to the count() value returned, can someone please tell me the correct syntax for that?

 

Thanks.

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
jungleeejungleee

You can use the database.countQuery method to get the count of the dynamic SOQL

 

integer  count= database.countQuery('select count() from account');

system.debug('the count is '+ count);

 

 

All Answers

chuckwalleychuckwalley

The result of the call is going to be an integer. I do something similar... 

 

Integer AlreadyThere =  [SELECT count()  

                                            FROM AccountContactRole__c  

                                            WHERE Account__c = :vACRobject.Account__c

                                            And Contact__c = :vACRobject.Contact__c  LIMIT 1];

 

Does that help? 

moverdorfmoverdorf

Your solution only works if it isn't dynamic SOQL.

 

I need to first create the Sobject based on the value of the Mystr, and then reference the count from the Sobject, which I am unsure how to so syntactically.

jungleeejungleee

You can use the database.countQuery method to get the count of the dynamic SOQL

 

integer  count= database.countQuery('select count() from account');

system.debug('the count is '+ count);

 

 

This was selected as the best answer
moverdorfmoverdorf

Thank you!

Danny SalvadoriDanny Salvadori
[SELECT count() FROM Account] // Returns Integer
^ Returns integer value.
Database.query('SELECT count() FROM Account') // Invalid!
^ INVALID! Using dynamic SOQL (i.e. String-based), you must use Database.countQuery()
Database.countQuery('SELECT count() FROM Account') // Returns Integer