title: trigger to populate/update these field on Account record whenever a new Contact, opportunity record is inserted or deleted
body: <p>Number fields on Account : "No of Contacts"
   Write trigger to populate/update field on Account record whenever a new Contact record is inserted or deleted.</p>
  
  <p>All is working fine but whenever i am deleting last contact record it is not updating Account field from 1 to 0
  Can anyone help me on this</p>
  
  <pre><code>trigger UpdateContactCountOnAccount on Contact (after insert, after update, after delete) 
  {
      Set&lt;Id&gt; AccountIds = new Set&lt;Id&gt;();
  
      if(!Trigger.isDelete)
      {
          for (Contact ct : Trigger.new) 
          {        
              if(Trigger.isInsert &amp;&amp; ct.AccountId != null)
              {
                  AccountIds.add(ct.AccountId);
              }
              if(Trigger.isUpdate)
              {
                  if(ct.AccountId==null &amp;&amp; Trigger.oldMap.get(ct.Id).AccountId != null)
                  {
                      AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId);
                  }
                  if(ct.AccountId!=null &amp;&amp; Trigger.oldMap.get(ct.Id).AccountId != null 
                                                                      &amp;&amp; ct.AccountId != Trigger.oldMap.get(ct.Id).AccountId)
                  {
                      AccountIds.add(ct.AccountId);
                      AccountIds.add(Trigger.oldMap.get(ct.Id).AccountId);
                  }
                  if(ct.AccountId!=null &amp;&amp; Trigger.oldMap.get(ct.Id).AccountId == null)
                  {
                      AccountIds.add(ct.AccountId);
                  }
              }
          }
      }
      else
      {
          for (Contact ct : Trigger.old)
          {
              if(Trigger.isDelete &amp;&amp; ct.AccountId != null)
              {
                  AccountIds.add(ct.AccountId);
              }
          }   
      }
  
      List&lt;Account&gt; AcctToUpdate = new List&lt;Account&gt;();
      for (AggregateResult ar: [Select Count(Id) ContactCount, AccountId 
                                from Contact where AccountId IN: AccountIds GROUP BY AccountId])
      {
          Account tmp = new Account(Id=(Id)ar.get('AccountId'), No_of_Contacts__c=(Decimal)ar.get('ContactCount'));
          AcctToUpdate.add(tmp);
      }
      if(AcctToUpdate.size()&gt;0) 
          update AcctToUpdate;
   }
  </code></pre>
  
  <p>All is working fine but whenever i am deleting last contact record it is not updating Account field from 1 to 0</p>