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
Ranjith YMRanjith YM 

Lead count based on Owner ID

I am trying to get count of lead assigned to User in APEX, there are 300+ leads assigned to each users, i can able to see when i query but same if i add in APEX code, its returning zero,

 for(User activeLO : activeLOs){
           Integer numberOfLeads = [select count() from Lead where OwnerId =:activeLO.Id];
            System.debug('Lead Count ::' +numberOfLeads );
       }

Ajay K DubediAjay K Dubedi
Hi Ranjith,

You can use the below code: 
 
public class apexclass {
    public static void countLead(){
        try{
            List<Lead> leadList = new List<Lead>();
            List<User> userList = new List<User>();
            userList = [SELECT Id, Name FROM User];
            leadList = [SELECT Id, OwnerId FROM Lead LIMIT 5000];
            Map<Id, List<Lead>> ownerIdVsLead = new Map<Id, List<Lead>>();
            if(leadList.size() > 0 && leadList != NULL){
                for(Lead leadObject : leadList){
                    if(!ownerIdVsLead.containsKey(leadObject.OwnerId)){
                        ownerIdVsLead.put(leadObject.OwnerId, new List<Lead>());
                    }
                    ownerIdVsLead.get(leadObject.OwnerId).add(leadObject);
                }
                
                for(Id leadObject : ownerIdVsLead.keySet()){
                    System.debug('UserId'+ownerIdVsLead.get(leadObject).size());
                }
                
            }
        }catch(Exception exp){
            System.debug('Exception Cause-->>'+exp.getMessage()+'Line Number-->>'+exp.getLineNumber());
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com