+ Start a Discussion
rahul Shukla 37rahul Shukla 37 

How to check Count of contact Even or Odd

Please help me on this question of SOQL
Find the account Specific account and check the number of contact associated with that account if the count of contact is odd add one more and make it even
Best Answer chosen by rahul Shukla 37
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rahul,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger EvenNumberOfConOnAcc on Contact (after insert, after update, after delete) {
    Set <Id> accountIds = new Set <Id>();
    List <Contact> lstToInsert = new List <Contact>();
        for(Contact con:trigger.new){
    if(Trigger.isUpdate|| Trigger.isDelete){
        for(Contact con:trigger.old){
    for(Account acc:[SELECT Id,Name,(Select Id from Contacts) from Account where Id IN: accountIds]){
        if(math.mod(acc.Contacts.size(), 2) != 0){
            Contact con = new Contact();
            con.LastName = acc.Name + 1;
            con.AccountId = acc.Id;
        INSERT lstToInsert;

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas