trigger to block more than 2 contacts per account. This trigger is working fine on after insert.

But I have confusion that it should be on before insert as we want this trigger to work before inserting account but on after insert this trigger is not working fine as even 100 contacts are getting created of a account by writing script.

trigger BlockMoreThan2ContactOnAccount on Contact (after insert, after update, after undelete) {
  Set<Id> accountIds = new Set<Id>();
  for(Contact record: Trigger.new) {
  Set<Id> morethan2Contacts = new Map<Id, AggregateResult>([
    SELECT AccountId Id
    FROM Contact
    WHERE AccountId = :accountIds
    GROUP BY AccountId
    HAVING COUNT(Id) > 2]).keySet();
  for(Contact record: Trigger.new) {
    if(moreThan2Contacts.contains(record.AccountId)) {
      record.AccountId.addError('You may not have more than 2 contacts per account.');

Plz check it once.. When this trigger is on before insert.. 3.4.5 n no of contacts are getting created by writing script

account acc=new account(); acc.name='df';

insert acc;

list con=new list(); for(integer i=0;i<3;i++) { contact c=new contact(); c.lastname='sd'; c.accountid=acc.id; con .add(c); } insert con


On before this script is working and contacts are getting created.. But on after insert contacts are not getting created. Can anyone clear the doubt

  • If you add 3 contacts in a single transaction, do you want them all to fail? or just the last 1?
    – Nick Cook
    Mar 1, 2021 at 5:34
  • yes i want them to fail all the three Mar 1, 2021 at 9:49

1 Answer 1


The code more or less works.

for(integer i=0;i<3;i++) checks for number of contacts < 3. While inserting the 3rd contact, the system is still seeing only 2 contacts in the database and therefore proceeds to insert the contact record. You will see failure for the next insertion though.

If you want to restrict only 2 contacts, change the SOQL group count to HAVING COUNT(Id) >= 2]).keySet().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.