Skip to main content

I need some clarification regarding the execution behavior of a before update trigger and roll-up summary fields on Account.

 

In my scenario, when child records are created, roll-up summary fields on the Account (such as Count and  Sent Date) are updated accordingly. Based on these values, I have implemented a before update trigger on Account to populate Status and latest Sent Date fields in the same object.

 

I would like to understand a few points before finalizing the implementation:

 

1. What are the key considerations when relying on roll-up summary fields within a before update trigger?

. 

2. Will the roll-up summary values (especially MAX date) always be reliably available during before update execution, or are there timing scenarios where they may still be null?

 

3. Is it recommended to handle this logic in a before update trigger, or would an after update trigger be more consistent for this use case?

 

4. Are there any best practices or known limitations when using roll-up summary fields to drive trigger logic, particularly during bulk data loads?

@* Salesforce Developers * 

2 件の回答
  1. 3月22日 22:37

    These are excellent questions about trigger timing and roll-up summary field behavior. Let me break down each consideration:

    1. Key Considerations for Roll-Up Summary Fields in Before Update Triggers

    Roll-up summary fields are calculated before the trigger fires, which makes them available in before update triggers. However, you need to be aware of:

    Calculation timing: Roll-ups are recalculated when child records are inserted, updated, deleted, or undeleted. The parent record's before update trigger fires after this recalculation.

    Same-transaction updates: If you're updating the Account directly in the same transaction (not via child records), roll-ups won't recalculate until child changes occur.

    Field availability: In Trigger.new, roll-up values reflect the recalculated state. In Trigger.old, they reflect the previous state.

    Governor limits: Roll-up calculations count toward SOQL query rows (when Salesforce retrieves child records internally).

    2. Reliability of Roll-Up Summary Values (MAX Date)

    Roll-up summary fields, including MAX aggregates, are reliably available in before update triggers when the trigger is fired due to child record changes. However, watch for these edge cases:

    Scenarios where values are reliable:

    Child record insert/update/delete/undelete operations

    Bulk operations on child records (the roll-up recalculates for all affected parents)

    Potential null scenarios:

    Initial Account creation: If no child records exist yet, MAX will be null

    All child records deleted: MAX will become null

    Field-level security: If the user can't see the child field being rolled up, behavior may vary

    Reparenting: When a child is reparented away, the old parent's roll-up recalculates (potentially to null)

    Best practice: Always null-check roll-up values in your trigger logic:

    APEX

    if (Trigger.isBefore && Trigger.isUpdate) {

    for (Account acc : Trigger.new) {

    Account oldAcc = Trigger.oldMap.get(

    acc.Id

    );

    // Null-safe check for roll-up changes

    if (acc.Rollup_Count__c != oldAcc.Rollup_Count__c ||

    acc.Rollup_Max_Sent_Date__c != oldAcc.Rollup_Max_Sent_Date__c) {

    if (acc.Rollup_Max_Sent_Date__c != null) {

    acc.Latest_Sent_Date__c = acc.Rollup_Max_Sent_Date__c;

    }

    // Status logic based on count

    if (acc.Rollup_Count__c > 0) {

    acc.Status__c = 'Active';

    } else {

    acc.Status__c = 'Inactive';

    }

    }

    }

    }

    3. Before Update vs. After Update Trigger

    For your use case, BEFORE UPDATE is the correct choice because:

    ✅ Advantages of Before Update:

    You can modify the Account record (Trigger.new) directly without requiring an additional DML operation

    More efficient (no extra update statement = better governor limit usage)

    Atomic operation (all changes saved in one transaction)

    No risk of recursion from updating the same record again

    ❌ After Update would require:

    An additional update DML statement to save your Status/Date changes

    Recursion prevention logic (to avoid infinite loops)

    Higher governor limit consumption

    Potential for additional trigger executions

    When to use After Update instead:

    When you need to update related records (not the triggering record itself)

    When you need the record's final committed state (including system fields like LastModifiedDate)

    When performing asynchronous operations (@future, Queueable, Platform Events)

    4. Best Practices & Known Limitations for Bulk Operations

    Best Practices:

    a) Bulkify your trigger logic:

    APEX

    trigger AccountBeforeUpdate on Account (before update) {

    // Use handler pattern

    AccountTriggerHandler.handleBeforeUpdate(Trigger.new, Trigger.oldMap);

    }

    APEX

    public class AccountTriggerHandler {

    public static void handleBeforeUpdate(List<Account> newAccounts,

    Map<Id, Account> oldAccountMap) {

    for (Account acc : newAccounts) {

    Account oldAcc = oldAccountMap.get(

    acc.Id

    );

    // Only process if roll-up fields changed

    if (hasRollupChanged(acc, oldAcc)) {

    updateStatusAndDate(acc);

    }

    }

    }

    private static Boolean hasRollupChanged(Account newAcc, Account oldAcc) {

    return newAcc.Rollup_Count__c != oldAcc.Rollup_Count__c ||

    newAcc.Rollup_Max_Sent_Date__c != oldAcc.Rollup_Max_Sent_Date__c;

    }

    private static void updateStatusAndDate(Account acc) {

    // Null-safe logic

    if (acc.Rollup_Max_Sent_Date__c != null) {

    acc.Latest_Sent_Date__c = acc.Rollup_Max_Sent_Date__c;

    }

    acc.Status__c = (acc.Rollup_Count__c > 0) ? 'Active' : 'Inactive';

    }

    }

    b) Avoid SOQL in loops:

    Your approach using roll-ups already avoids this ✅

    Don't query for child records again; trust the roll-up values

    c) Test with bulk data:

    APEX

    @IsTest

    private class AccountTriggerTest {

    @IsTest

    static void testBulkChildInsert() {

    // Create 200 Accounts

    List<Account> accounts = new List<Account>();

    for (Integer i = 0; i < 200; i++) {

    accounts.add(new Account(Name = 'Test ' + i));

    }

    insert accounts;

    // Create 200 child records (adjust to your object)

    List<Child__c> children = new List<Child__c>();

    for (Account acc : accounts) {

    children.add(new Child__c(

    Account__c =

    acc.Id

    ,

    Sent_Date__c = Date.today()

    ));

    }

    Test.startTest();

    insert children; // This triggers Account before update

    Test.stopTest();

    // Verify roll-up triggered status update

    List<Account> updatedAccounts = [

    SELECT Status__c, Latest_Sent_Date__c, Rollup_Count__c

    FROM Account

    WHERE Id IN :accounts

    ];

    for (Account acc : updatedAccounts) {

    System.assertEquals('Active', acc.Status__c);

    System.assertEquals(Date.today(), acc.Latest_Sent_Date__c);

    System.assertEquals(1, acc.Rollup_Count__c);

    }

    }

    }

    Known Limitations:

    a) Roll-Up Summary Limits:

    Maximum 25 roll-up summary fields per object

    Maximum 10 roll-up summary fields per object that use SOQL aggregate functions (COUNT, SUM, MIN, MAX)

    Child object must be on the detail side of a master-detail relationship

    b) Bulk Load Considerations:

    Data Loader: Roll-ups recalculate normally; your trigger will fire for each batch

    Batch size: Keep batches at 200 or less to avoid governor limits

    Parallel processing: If using Bulk API with parallel mode, be aware of lock contention on parent records

    Recalculation delays: In very large bulk loads, there can be slight delays, but values are consistent once the trigger fires

    c) Performance:

    Roll-up recalculation happens synchronously and can slow down child record DML in high-volume scenarios

    Consider whether you truly need real-time accuracy or if a scheduled batch recalculation would suffice

    d) Recursion scenarios:

    If your before update trigger modifies fields that could trigger workflows/process builders that update child records, you could create a loop

    Implement recursion prevention if needed:

    APEX

    public class TriggerRecursionHelper {

    private static Set<Id> processedAccountIds = new Set<Id>();

    public static Boolean isFirstRun(Id accountId) {

    if (processedAccountIds.contains(accountId)) {

    return false;

    }

    processedAccountIds.add(accountId);

    return true;

    }

    }

    Summary Recommendation

    Your implementation approach is sound:

    ✅ Use before update trigger to populate Status and Latest Sent Date

    ✅ Roll-up summary values will be available and reliable

    ✅ Always null-check roll-up values

    ✅ Only update fields when roll-up values actually change (compare with Trigger.oldMap)

    ✅ Bulkify your logic and test with 200+ records

    ✅ Use the handler pattern for maintainability

    ⚠️ Monitor for recursion if you have other automation on Account or child objects

    This pattern is efficient, governor-limit friendly, and will handle bulk operations reliably.