Skip to content
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24globalworld |
  • News24classictimes |
  • Incriediableindia |
  • TechW3web |
  • W3Force ..
w3web.net
Sign Up to Get Free Code Access โ†’ |
  • Home
  • Tutorial
    • Lightning Component
    • Salesforce LWC
    • Salesforce Integration
    • Visualforce
    • Trigger
    • JQuery
  • Get Free Courses
  • Integration
  • Aura Comp
  • Salesforce LWC
  • Visualforce
  • Trigger
  • JQuery
  • React Js
  • More
    • About Us
    • Contact Us
    • Sitemap
    • Course Pricing
    • Blog
    • Gallery
    • Most Popular Articles
    • Download E-Book
    • YouTube Channel


Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.

February 12, 2026February 10, 2026 by Vijay Kumar
95 views

Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.

 

Create Custom Fields on Account

Create 4 Number fields on Account:

๐Ÿ‘‰ Download Free Ebook โ†’

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
Field Label API Name
India Contacts Count India_Contacts__c
USA Contacts Count USA_Contacts__c
England Contacts Count England_Contacts__c
Japan Contacts Count Japan_Contacts__c

Data Type โ†’ Number (0 Decimal Places)

Logic Approach (Best Practice โ€“ Bulkified)

  • Use after insert
  • Use after update
  • Use after delete
  • Use after undelete
  • Collect all AccountIds
  • Run Aggregate Query
  • Update Account

 

 

Step 1 Account Trigger (After Update): ContactPracticeTrigger.apxt

  1.    TRIGGER AggregateResultContactPractice ON Contact (BEFORE INSERT, after INSERT, BEFORE UPDATE, after UPDATE, BEFORE DELETE, after DELETE, after undelete) {
  2.  
  3.   //COUNT child Contacts related TO each Account Based ON MailingCountry ONLY FOR these 4 countries:India, USA, England, AND Japan 
  4.  
  5.     //THEN store the COUNT ON Account object: India_Contacts__c, USA_Contacts__c, England_Contacts__c, Japan_Contacts__c 
  6.  
  7.     IF(TRIGGER.isAfter){
  8.  
  9.            Set<Id> accountIds = NEW Set<Id>();
  10.  
  11.             IF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
  12.                 FOR(Contact con:TRIGGER.new){
  13.                     IF(con.AccountId != NULL){
  14.                         accountIds.add(con.AccountId);
  15.                     }
  16.                 }
  17.  
  18.             }
  19.  
  20.             IF(TRIGGER.isDelete || TRIGGER.isUpdate ){
  21.                 FOR(Contact con2:TRIGGER.old){
  22.                     IF(con2.AccountId != NULL){
  23.                         accountIds.add(con2.AccountId);
  24.                     }
  25.                 }
  26.  
  27.             }
  28.  
  29.  
  30.          List<AggregateResult> agrList = [SELECT AccountId, MailingCountry, COUNT(Id) totalCount FROM Contact WHERE AccountId IN:accountIds AND MailingCountry IN ('India','USA','England','Japan') GROUP BY AccountId, MailingCountry ];
  31.  
  32.           Map<Id, Integer> IndiaMap = NEW Map<Id, Integer>();
  33.           Map<Id, Integer> UsaMap = NEW Map<Id, Integer>();
  34.           Map<Id, Integer> EnglandMap = NEW Map<Id, Integer>();
  35.           Map<Id, Integer> JapanMap = NEW Map<Id, Integer>();            
  36.  
  37.             FOR(AggregateResult ar:agrList){
  38.                Id ids = (Id) ar.get('AccountId');
  39.                String country = (String) ar.get('MailingCountry');
  40.                INTEGER countValue = (INTEGER) ar.get('totalCount');
  41.  
  42.                 IF(country == 'India'){
  43.                     IndiaMap.put(ids, countValue);
  44.                 } 
  45.  
  46.                 ELSE IF (country == 'USA'){
  47.                     UsaMap.put(ids, countValue);
  48.                 }
  49.  
  50.                 ELSE IF (country == 'England'){
  51.                     EnglandMap.put(ids, countValue);
  52.                 }
  53.  
  54.                 ELSE IF (country == 'Japan'){
  55.                     JapanMap.put(ids, countValue);
  56.                 }
  57.  
  58.             }
  59.  
  60.  
  61.             List<Account> accItem = NEW List<Account>();
  62.  
  63.             FOR(Id accId:accountIds){               
  64.                 Account accObj = NEW Account();
  65.                 accObj.India_Contacts__c = IndiaMap.get(accId);
  66.                 accObj.USA_Contacts__c = UsaMap.get(accId);
  67.                 accObj.England_Contacts__c = EnglandMap.get(accId);
  68.                 accObj.Japan_Contacts__c = JapanMap.get(accId);               
  69.                 accObj.Id = accId;
  70.                 accItem.add(accObj);
  71.             }
  72.  
  73.             IF(!accItem.isEmpty()){
  74.                 UPDATE accItem;
  75.             }
  76.  
  77.  
  78.     }
  79.  
  80.  
  81. }

 

How This Works (Step-by-Step):

  • Collect Account IDs from Trigger context
  • Run one Aggregate SOQL query
  • Group by AccountId and MailingCountry
  • Store result in Map
  • Update Account with country-wise count
  • If no contacts โ†’ set count = 0

 

Why This is Interview-Ready?:


๐ŸŽ Up to 99% Off Courses (Coupon)
๐Ÿ’ฅ Use Promo Code: STANDARDOFFER๐Ÿ’ฅ
๐Ÿš€ Get Free Salesforce Course Access: www.thevijaykumar.w3web.net
  • Fully Bulkified
  • Uses Aggregate Query
  • Handles Insert/Update/Delete/Undelete
  • No SOQL inside loop
  • No DML inside loop

 

Further post that would you like to learn in Salesforce

  • Trigger on contact to update a account custom field | Write a trigger on contact and update the account custom field uses of apex trigger in Salesforce
  • Create a Apex Trigger on Account to Update the Associated Contact Account Name Null Whenever Account Record is Updated in Salesforce
  • Trigger to check duplicate name to custom object in Salesforce | how to prevent duplicate records based on multiple fields through apex trigger in Salesforce
  • Write a Apex trigger to Add the Contact First Name and Last Name to Associated Account Custom Field Whenever the Contact inserted or Updated in Salesforce
  • Trigger to update parent records field when child record is updated | update parent field from child using apex trigger
  • How to call invocable method (@InvocableMethod) from APEX Controller to convert automatic lead to Account, Contact and Opportunity Uses of Flow Builder/Flow Action in Salesforce
  • Write a trigger to update parent account phone number whenever the contact phone number is updated using trigger handler and helper class in Salesforce
  • Trigger on custom object to prevent delete the related list record based on lookup relation whenever trying to delete parent record, throw an error message using apex class handler trigger in Salesforce
  • Write a trigger on lead to prevent duplicate records based on lead email Whenever the records is inserted Or updated using apex class handler trigger in Salesforce
  • Apex Trigger on Contact to Create Account Automatically and map to related account Id to Contact Whenever New Contact is Created in Salesforce

 

FAQ (Frequently Asked Questions)

Can a contact be associated with multiple accounts in Salesforce?

Enabling Account Contact Relationship access mapping feature allows your sales reps to easily track the relationships between the customers and businesses they work with. It's quick to set up and allow reps to relate a single contact record to multiple accounts.

How are contacts and accounts related in Salesforce?

The relationship rules are still simple. Every contact needs to be directly associated with an account. This is the account that appears in Account Name and is usually the company the contact is most closely associated with. Any other accounts associated with the contact represent indirect relationships.

What happens to related records when you merge accounts in Salesforce?

What happens to related records when accounts are merged? All related recordsโ€”contacts, opportunities, casesโ€”are automatically transferred to the master account. Note that conflicting fields require manual selection of which data to retain.

Related Topics | You May Also Like

  • Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, AdvertisementApex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement
  • Write Apex Trigger on Account to Count the number of Contact records using Map in Salesforce | Apex trigger on Account to create and count the number of Contact records associated with Account object based on custom field when Account record is created/updated in SalesforceWrite Apex Trigger on Account to Count the number of Contact records using Map in Salesforce | Apex trigger on Account to create and count the number of Contact records associated with Account object based on custom field when Account record is created/updated in Salesforce
  • Trigger to update count of child records with custom field of parent object | count of child records on parent for lookup relationship uses of apex trigger in SalesforceTrigger to update count of child records with custom field of parent object | count of child records on parent for lookup relationship uses of apex trigger in Salesforce
  • Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on AccountApex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account
  • Update Parent field when Child record is Updated or Inserted in Salesforce | Trigger updating parent with child value when a field on the child is changedUpdate Parent field when Child record is Updated or Inserted in Salesforce | Trigger updating parent with child value when a field on the child is changed
  • Write a trigger on contact to update parent record when child is updated using apex trigger in Salesforce | How to write trigger to update account Phone when contact Phone is updated in SalesforceWrite a trigger on contact to update parent record when child is updated using apex trigger in Salesforce | How to write trigger to update account Phone when contact Phone is updated in Salesforce
  • Write a Apex trigger to Add the Contact First Name and Last Name to Associated Account Custom Field  Whenever the Contact inserted or Updated in Salesforce | Trigger to update Associated Account Custom FieldWrite a Apex trigger to Add the Contact First Name and Last Name to Associated Account Custom Field Whenever the Contact inserted or Updated in Salesforce | Trigger to update Associated Account Custom Field
  • When an Accountโ€™s field Share_With_User__c (a lookup to User) is filled, automatically share that Account with that user via Apex sharing.When an Accountโ€™s field Share_With_User__c (a lookup to User) is filled, automatically share that Account with that user via Apex sharing.

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
 
  
๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Vijay Kumar

Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Categories Uncategorized Tags Apex trigger to count child contacts related to each account interview, count of child records on parent for lookup relationship, parent child trigger scenarios, Salesforce count number of contacts in Account, Trigger on account and contact in salesforce, Trigger to count number of contacts associated with an account using aggregate query, Trigger to find sum of all related opportunities amount of an account, Trigger with handler class example
When an Accountโ€™s field Share_With_User__c (a lookup to User) is filled, automatically share that Account with that user via Apex sharing.
Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement

Archives โ†’

Categories โ†’

  • Agentforce (4)
  • Blog (4)
  • More (7)
  • Tutorial (326)
    • Formula Field (1)
    • JQuery (13)
    • Lightning Component (60)
    • React Js (15)
    • Salesforce Integration (41)
    • Salesforce LWC (115)
    • Trigger (57)
    • Validation Rule (9)
    • Visualforce (16)
  • Uncategorized (4)

Global Visitors โ†’

Popular Posts โ†’

  • Salesforce REST API Integration Using Postman โ€“ Complete Tutorial | Understanding How to Call Salesforce Web Service | Salesforce REST API: A Step-by-Step Guide | Tech W3Web 3.33 views per day
  • add page header or footer into a visualforce -- w3web.net How to make header and footer fixed and repeat on Visualforce page rendered as PDF in Salesforce | How to add header and footer in Visualforce page rendered as PDF in Salesforce 3 views per day
  • trigger to create account Automatically whenever contact is is created -- w3web.net Apex Trigger on Contact to Create Account Automatically and map to related account Id to Contact Whenever New Contact is Created in Salesforce | trigger to create account automatically whenever contact is created in salesforce 2.50 views per day
  • create lightning datatable row actions in lwc -- w3web.net Creating a Lightning Datatable with Row Actions and Display a Modal Popup on Click View Icon Button in Salesforce Lightning Web Component – LWC | how to create lightning datatable row actions in lwc 2.33 views per day
  • create form fields horizontally in lwc -- w3web.net How to align lightning-input form elements horizontally uses of slds-form-element_horizontal css and lightning-card tag in Lightning Web Component – LWC | How to create horizontal input label using slds-form-element/slds-form-element_horizontal... 2.33 views per day
  • Do not allow delete Account, if any of related Contact associated with Account in Salesforce | Prevent the deletion of Account which have related contact through apex trigger in Salesforce 2.33 views per day
  • display different types of toast message in lwc -- w3web.net How to display different types of custom toast message as Error, Success, Info and warning toast notifications on click button, uses of ShowToastEvent property in Salesforce Lightning Web Component — LWC | display custom toast notification in... 2 views per day
  • change stateful button value in lwc -- w3web.net How to change the state of button value as ‘follow/unfollow’ or ‘like/dislike’ through onclick handler method uses of ‘lightning-button-stateful’ tag elements in Salesforce LWC (Lightning Web Component) | How to c... 2 views per day

Get Free Courses โ†’

right side banner -- www.surfmyindia.com
right side banner -- overstockphoto.blogspot.com

Join Our Newsletter โ†’

Loading
right side banner -- www.lifedreamguide.com

Recent Posts โ†’

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account
right side banner -- www.w3webmart.com


header banner -- www.overstockphoto.blogspot.com
  • Follow Me โ†’
โžก : Facebook
โžก : Twitter
โžก : Linkedin
โžก : Instagram
โžก : Reddit
โžก : Forcetalks
โžก : Pinterest
โžก : Github
โžก : Medium
โžก : Tumblr
โžก : Telegram
 

๐Ÿงฉ Get Free Courses

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
header banner -- www.overstockphoto.blogspot.com

Recent Posts โ†’

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account
  • Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account
  • Apex Trigger Whenever Opportunity is Inserted/Updated/Deleted/Undeleted We need to count how many Opportunities have: StageName = ‘Closed Won’ And update that count on Account.
  • Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement
header banner -- www.lifedreamguide.com

Popular Posts โ†’

  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce 7 views
  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce 6 views
  • create lightning-card container with custom tab in lwc -- w3web.net How to create lightning-card container with custom tab functionality uses a button in the actions slot where we are opening a lightning popup inside a custom form, displaying plain text in the footer slot in Salesforce LWC | How to apply lightning-card to create stylized container around a grouping of information to display different section like Header, Body, Footer and button actions with open a popup inside form in Salesforce LWC (Lightning Web Component) 3 views
  • How to Navigate to External Web Page in LWC – Lightning Web Component | How to use Navigation Service (NavigationMixin.Navigate) to Navigate to External Web Page in LWC 3 views
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24classictimes |
  • TechW3web |
  • Refund Policy |
  • Delivery Policy |
  • Privacy Policy |
  • Term & Conditions
© 2026 w3web.net • Built with GeneratePress

Chat Now