Query Users from Public Group in Apex

This post will walk you through the implementation of how to Query Users from Public Group in Apex in Salesforce. A Public Group can contain multiple Users, Roles, Roles and Subordinates, and other Public Groups.

In this implementation, we will get Users from the Public Group in Apex. Let’s get into the implementation.

Query Users from Public Group in Apex

To Query Users from the Public Group in Apex, we first need to query the Public Group using either Name or Id. For that, write a simple query on the Group Sobject with the type = ‘Regular’.

[SELECT Id FROM Group WHERE Name= 'Test Public Group' and Type = 'Regular' LIMIT 1]

Here, we are querying the Public Group with the ‘Test Public Group’ name.

Then, we need to write a query on the GroupMember SObject to get the Users.

[SELECT GroupId, UserOrGroupId FROM GroupMember WHERE GroupId = 'Id of Group that we got in earlier query']

Now, we must remember that the Public Group can contain Roles, Roles and Subordinates, and other Public Groups as well.

In order to get only the users from the Public Group, we need to check if the UserOrGroupId starts with ‘005’. Because User Id always starts with ‘005’.

This is how our apex code would look like to get Users from Public Group in Apex:

List<Group> lstPublicGroup = [SELECT Id FROM Group WHERE Name= 'Test Public Group' and Type = 'Regular' LIMIT 1];
if(lstPublicGroup != null && !lstPublicGroup.isEmpty()){
    for(GroupMember objMember : [SELECT GroupId, UserOrGroupId FROM GroupMember WHERE GroupId = :lstPublicGroup[0].Id]){
        if(String.valueOf(objMember.UserOrGroupId).startsWith('005')){
            System.debug('User Id : ' +objMember.UserOrGroupId);
        }
    }
}

Also Read:

Output

Below is the screenshot of Test Public Group in my Org.

Query Users from Public Group in Apex
Query Users from Public Group in Apex

As you can see, there are only two users added to this Public Group.

And below is the output after executing the above code in the Anonymous window:

get Users from Public Group in Apex
get Users from Public Group in Apex

Also Read:

That is all from this post. This is how we can get Users from Public Group in Apex in Salesforce.

If you don’t want to miss new implementations, please Subscribe here.

To know more about what fields are available on the Group Sobject, check official Salesforce documentation here.

See you in the next implementation. Thank you!

Leave a Comment