Posts

Showing posts from March, 2025

Apex Batch Class to Count Contacts for Each Account .

  🔹 Apex Batch Class to Count Contacts for Each Account & Update Contact_Count__c Field This Apex Batch Class efficiently counts all Contacts associated with each Account and updates the Contact_Count__c field. ✅ Bulk-Safe & Scalable for Large Datasets ✅ Optimized SOQL Queries Using Maps ✅ Handles Millions of Records Efficiently ✅ Follows Salesforce Best Practices 🔹 Step 1: Add a Custom Field to Account Before using this batch job, create a custom field on the Account object: Field Name : Contact_Count__c Type : Number (18,0) 🔹 Step 2: Apex Batch Class public with sharing class BatchAccountContactCounter implements Database.Batchable<SObject>, Database.Stateful { // Map to store Account ID -> Contact Count private Map<Id, Integer> accountContactCountMap = new Map<Id, Integer>(); /** * Query all Accounts that need Contact Count updates */ public Database.QueryLocator start(Database.BatchableCon...

Apex Salesforce: Count the associated child records to parent record

 Below is the Apex class to count all child records associated with a parent record, ensuring: ✅ Bulk-safe operations ✅ Optimized SOQL queries (avoiding loops inside queries) ✅ Efficient use of Maps to reduce processing time 🔹 How This Code is Optimized Uses Maps for O(1) Lookup : Stores parent IDs with a default count of 0 to avoid missing entries. Avoids SOQL Queries in Loops : Uses a single SOQL query with GROUP BY to count child records efficiently. Bulk-Safe & Scalable : Accepts a list of parent IDs to handle multiple records in a single execution. Dynamic Query Construction : Works with any parent-child object pair by passing object names dynamically. Exception Handling : Validates input parameters to prevent runtime errors.