+ Start a Discussion
Akansha Yadav 3Akansha Yadav 3 

Help in optimizing the code

List<Account> accs = [SELECT Id, Is_Paid__c FROM Account WHERE PersonContactId=:conIds];
    if(accs!=null && !accs.IsEmpty())             
    {
       for(Account acc : accs)
       {
             acc.Is_Paid__c = true;     
        }
        if (accs!=null && !accs.IsEmpty())  
            {
                 update accs;
             } 
      }
 
Akansha Yadav 3Akansha Yadav 3
Also i would like to know Is it necessary to check for null and IsEmpty ? 
Rafael.Martins.SantosRafael.Martins.Santos
Hi Akansha,

Try this code:

    for(Account acc : [SELECT Id, Is_Paid__c FROM Account WHERE PersonContactId=:conIds]){
         if (acc.FIELD !=null){
             acc.Is_Paid__c = true;     
             update acc;
        }
    }

Best Regards
Rafael
Rafael.Martins.SantosRafael.Martins.Santos
Depends of what you Trying to verify.
If you need check if exist some register that have relationship with "conIds", you don't need check if is null or not.
Shruti SShruti S
The List<Account> has not been instantiated, hence you cannot use .isEmpty() on the List<Account> (accs). And there is no need to do null check two times.
Below is the optimized code.
List<Account> accs = 
    [
        SELECT  Id 
                ,Is_Paid__c 
        FROM    Account 
        WHERE   PersonContactId = :conIds
    ];

if( accs!= NULL ) {
    for( Account acc : accs ) {
        acc.Is_Paid__c = TRUE;     
    }
    UPDATE accs;
}
Anjita MaheshwariAnjita Maheshwari
Hi Akansha,

Here is an approach to make above update:
List<Account> accs =  new List<Account>();
for(Account acc : [SELECT Id, Is_Paid__c FROM Account WHERE PersonContactId=:conIds]){
    acc.Is_Paid__c = true;
    accs.add(acc);
}

if(accs.size() > 0){
    update accs;
}

This is a good approach to use SOQL query in for loop. Second thing, you just need a size check of list before updating the records. Please let me know if it helps.

Thanks,
Anjita