I have written a small Apex class to fetch list of all available (Standard+Custom) Objects in Org and their fields.

But when trying to retrieve total record of individual Object, this is showing too many SOQL issue. I understand this is happening due to the Query inside For{}. Is there any other way to fetch All Objects' total records.

Map<String, Schema.SObjectType> GlobalMap = Schema.getGlobalDescribe();         
        for (Schema.SObjectType Obj : GlobalMap.values()) {
            Schema.DescribeSObjectResult ObjDesc = Obj.getDescribe();
        system.debug(' Object Name   : ' + ObjDesc.getName()); 
        system.debug(' Object Fields : ' + ObjDesc.fields.getMap().keySet().size());    
        AggregateResult arRecs = Database.query('Select count(id) nRecs from '+ObjDesc.getName());
        system.debug(' Total Records : ' + Integer.valueOf(string.valueOf(arRecs.get('nRecs'))));               

  • 1
    You can go to (classic) Setup -> Company Information -> Company Profile. Somewhere on this page it shows your data usage, the value is a link. If you click this link you are directed to a page that shows exact data usage based on number of records of all entities. Nov 22, 2018 at 12:16
  • Do you need the count of records in code, or just want to see it on the Salesforce UI? Nov 22, 2018 at 12:17
  • This line of query is also going to get you a whole bunch of records you probably don't want to count, for example I believe ApexClass is included in getGlobalDescribe so you would include the number of Apex Classes in your org in your count. Nov 22, 2018 at 12:59
  • Yes @SaketJoshi , I have to prepare a CSV with Object Name ans its total Records and send email by Apex. Please let me know is there anyother way to address this. Nov 22, 2018 at 15:34

1 Answer 1


You can use the Iterable interface to your rescue. Here's how you can do that -

  1. Create a List with all the object API names you get from describe call
  2. Do check if the object can be queried, only then add it to the list
  3. Create a new batch class that implements Database.Batchable
  4. Instead of returning a List like a normal batch would do, return Iterable from the start() method
  5. Use the iterator (object API name) from your execute() method and query for that object
  6. Store the count for this object somewhere for use in future method so as to send the email

Remember to implement Database.Stateful as well, since you'll have to maintain the state of counts of all the objects

A similar implementation is given as an example here - https://andyinthecloud.com/2013/08/11/batch-worker-getting-more-done-with-less-work/

Instead of using List<String> { 'Do something', 'Do something else', 'And something more' }; in the start method, form a list of all object API names.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .