+ Start a Discussion
Athira VenugopalAthira Venugopal 

SHOWING AS System.QueryException

public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'];
Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}
I am trying to update the 'Number of contacts' field in Account object.
Tried to call the countContacts() from anonymous window, But this exception occurs
AccountProcessor.countContacts();
Best Answer chosen by Athira Venugopal
Athira VenugopalAthira Venugopal
I tried it, but shows an error like this
"Expression must be a list type: Account"
So I tried like this:

public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'][0];
        Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}

and it works, anyway thanks.

All Answers

Abhishek BansalAbhishek Bansal
Hi Athira,

Please use the updated code below:
public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'];
Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc[0].Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}

Thanks,
Abhishek Bansal.​​​​​​​
Athira VenugopalAthira Venugopal
I tried it, but shows an error like this
"Expression must be a list type: Account"
So I tried like this:

public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'][0];
        Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}

and it works, anyway thanks.
This was selected as the best answer
Abhishek BansalAbhishek Bansal
Hi Athira,

Yes this SOQL [Select Id, Name from Account where name = 'chandra'] will return a list so either you need to store the result in a list or you can take the first record in your account variable.
Please close the question so that it can help others in future.

Thanks,
Abhishek Bansal.