So we all know we can put an aggregate directly into an Integer, like this:

Integer countAccounts = [SELECT COUNT() FROM Account];

Is it possible to do the same thing, using Database.query()?

Integer countAccounts = Database.query('SELECT COUNT() FROM Account');

If so - how?

up vote 5 down vote accepted

Yes. You can query using Database.countQuery(query)

String QueryString = 'SELECT count() FROM Account'; 
Integer countAccounts  = Database.countQuery(QueryString);
  • Holy shit. That was surprisingly simple. Sometimes it surely helps to read the docs. Thanks! – Semmel Nov 20 at 16:39
  • @Semmel Of course it does! – codeyinthecloud Nov 20 at 16:39

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.