+ Start a Discussion
SandrineSandrine 

how to check if the accounts has no contacts

Hello,

In apex, How to check if the account has not contacts in it ?

 
Best Answer chosen by Sandrine
Dilip_VDilip_V
Sandrine,

Try this code
 
List<Account> Accounts=[select id,name,(select id,Lastname from contacts) from Account];
for(Account Acc:Accounts)
{
if(Acc.Contacts.size()>0)
{
//Contact exists for acc
}
else
{
//No contact for Acc
}
}

Let us know if it works.

Mark it as best answer if it helps.
Thanks.

All Answers

Dilip_VDilip_V
Sandrine,

Try this code
 
List<Account> Accounts=[select id,name,(select id,Lastname from contacts) from Account];
for(Account Acc:Accounts)
{
if(Acc.Contacts.size()>0)
{
//Contact exists for acc
}
else
{
//No contact for Acc
}
}

Let us know if it works.

Mark it as best answer if it helps.
Thanks.
This was selected as the best answer
SandhyaSandhya (Salesforce Developers) 
Hi Sandrine,

You can use SOQL to retrieve the accounts with no contacts.
 
select Id,name from Account where Id not In (select AccountId from Contact)

Hope this helps you!

If this helps you please mark it as solved.

Thanks and Regards
Sandhya
SandrineSandrine
hi

How can i check if the contacts have email id
 
List<Account> Accounts=[select id,name,(select id,Lastname from contacts) from Account];
for(Account Acc:Accounts)
{
if(Acc.Contacts.size()>0)
{
//Contact exists for acc
}
else
{
//No contact for Acc
}
}