I have a requirement to get all sponsor ids from Process record and store it on User record as multi-select picklist values.

below is my logic:

list<user> user = [SELECT ID from User where name = 'Test User']; 
List <Process__c> Processlist = [
  SELECT ID,Sponsor__c 
  FROM Process__c 
  Where User_Name__c = :user];

List<string> allProsList = new list<string>();
for (Process__c Process : Processlist) {
for(User us : user){
    us.Sponsor_Ids__c = String.join(allProsList,';');

Now, using this logic, I am getting duplicate Sponsor values. Suppose, if there are 100 Process records with same Sponsor Ids, i am seeing 100 Sponsor IDs on User record.

Is there anyway that i can get unique Sponsor id from Process object and store it in User record. Here, Process is child and Sponsor is Parent

Please suggest


Use a Set <String> in place of List<String>. Using a set will remove all duplicate instances of the Sponsor Id (Sponsor__c)

Set<string> allProsList = new Set<string>(); //List<string> allProsList = new list<string>();
for (Process__c Process : Processlist) {

allProsList will contain distinct set of Sponsor__c values.

Hope this helps.

//Pseudo code to bulkify the code - 
listProcess = [SELECT Id,User_Name__c FROM Process__c WHERE <Add Filter conditions other than "User_Name__c =" as we will query the users in the next step>];
Set<Id> userId;
for(Process p : listProcess){
userId.add(p.User_Name__c); //This is the set of user Ids related to the Process records

//This is the list of Users related to the Process Records. userList = [SELECT Id FROM User Where Id IN: userId]; // Update Sponsor Ids on this list.

  • 1
    Do note that String.join() still requires a List. Thankfully, it's easy to convert a Set to a List as List has a constructor that takes a Set, new List<String>(mySet)
    – Derek F
    Jun 9 '21 at 14:03
  • Thanks @Shashank.. Is there anyway I can query only those users which are present Process object instead of fetching and updating all of them?
    – SFDCUser
    Jun 9 '21 at 14:47
  • @SFDCUser It depends how are you invoking the process. Is it a trigger on Process object? You need to provide more details regarding your problem. Jun 9 '21 at 16:23
  • I am performing the update operation from Anonymous window as this is a one time process
    – SFDCUser
    Jun 9 '21 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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