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
Apurve SrivastavaApurve Srivastava 

i am getting error "System.QueryException: List has no rows for assignment to SObject"

i am getting error "System.QueryException: List has no rows for assignment to SObject"  in 

List<Account> ac = [SELECT Id,Name,(SELECT LastName FROM Contacts) FROM Account WHERE Name = 'Acme'];
List<Contact> con = new List<Contact>();
for(Account a : ac){    
     System.debug(a.Contacts);
    if(a.Contacts == null){
        System.debug('null');
    }
    else{
        con.add(a.Contacts);
    }
}

 plz tell me how i can fill null value in my con list

 
Mahesh NirmalMahesh Nirmal

Hi
It means your SOQL didn’t return any results. You can wrap it in a try/catch statement to handle this Exception.

please refer the below code.

List<Contact> con = new List<Contact>();
try{
List<Account> ac = [SELECT Id,Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = 'Acme'];
system.debug('ac'+ac);
    if(ac.size()>0){
for(Account a : ac){ 
    if(a.Contacts == NULL){
        System.debug('null');
    }
    else{
        con.add(a.Contacts);
        system.debug('con'+con);
    }
}
    }
}catch (System.QueryException e) {
  System.debug('Exception occured');
}

Devi ChandrikaDevi Chandrika (Salesforce Developers) 
This error is beacause your are not getting any results from the SOQL.
It is always a best practice to check if the list is empty before using it .So here just use if statement to check if the list is empty or not before using it in for loop.
 
List<Account> ac = [SELECT Id,Name,(SELECT LastName FROM Contacts) FROM Account WHERE Name = 'Acme'];
        List<Contact> con = new List<Contact>();
        if(ac.size()>0){
        for(Account a : ac){    
            System.debug(a.Contacts);
            if(a.Contacts == null){
                System.debug('null');
            }
            else{
                con.add(a.Contacts);
            }
        }
    }
Please refer below link which might help you further
https://help.salesforce.com/articleView?id=000328824&type=1&mode=1

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards