is live. Lifetime & Yearly plans on offer. thankful for you ๐Ÿงก

Get the Black Friday deal

Blog

How to Bulkify an Apex Trigger (With Before and After Examples)

Bulkify an Apex trigger by moving SOQL and DML out of loops. Before and after code, a Map-based fix, and a 250-record test class.

By Teja, ex-Salesforce engineer ยท Updated November 24, 2026 ยท 9 min read

How to Bulkify an Apex Trigger (With Before and After Examples)

To bulkify an Apex trigger, write it so it handles a whole list of records the same way it handles one. In practice that means no SOQL queries and no DML statements inside a for loop. First collect the Ids you need into a Set, then run one query and store the results in a Map keyed by Id, then put all your changes into a List and save it with one DML statement. Salesforce sends records to a trigger in chunks of up to 200, so a trigger that runs one query per record goes over the 100-query limit long before the chunk is finished.

The rest of this article shows a broken trigger, the bulkified version, a pattern for update triggers, and a test class that inserts 250 records to prove the fix works.

What bulkification means in Apex

A trigger never receives a single record. It receives Trigger.new, a list. When a user saves one Case from the UI, that list has one item. When a Data Loader job, an integration, a Flow, or another trigger inserts 1,000 Cases, Salesforce splits them into chunks of 200 and runs your trigger once per chunk.

Every chunk in the same Apex transaction shares one set of governor limits. If your code inserts 1,000 records with one insert statement, the trigger runs five times and all five runs count against the same 100-query budget. A trigger that uses one query per chunk spends 5 queries. A trigger that uses one query per record fails on record 101.

These are the synchronous per-transaction limits that bulkification protects you from:

Governor limit (per transaction)SynchronousAsynchronousWhat breaks it in a trigger
SOQL queries issued100200A query inside for (X x : Trigger.new)
Records retrieved by SOQL50,00050,000Querying without a WHERE ... IN :ids filter
DML statements issued150150insert/update inside a loop
Records processed by DML10,00010,000Very large cascades of related records
CPU time10,000 ms60,000 msNested loops that match records by hand

Check Salesforce's "Execution Governors and Limits" page for the current numbers before you build anything close to these ceilings. For a closer look at the most common failure, System.LimitException: Too many SOQL queries: 101, read Apex Bulkification: Fix 'Too Many SOQL Queries: 101'.

Before: a trigger that works for one record and fails for 200

Requirement: when a Case is created against an Account, create a follow-up Task for the Account's owner.

This version passes a manual test in the UI and fails in production the first time someone imports Cases:

trigger CaseTrigger on Case (after insert) {
    for (Case c : Trigger.new) {
        if (c.AccountId != null) {
            // SOQL inside the loop: one query per Case
            Account acc = [
                SELECT Id, OwnerId
                FROM Account
                WHERE Id = :c.AccountId
            ];

            Task t = new Task(
                WhatId       = c.Id,
                OwnerId      = acc.OwnerId,
                Subject      = 'Review new case ' + c.CaseNumber,
                ActivityDate = Date.today().addDays(1)
            );

            // DML inside the loop: one insert per Case
            insert t;
        }
    }
}

What goes wrong:

  1. The SOQL query runs once per record. At record 101 the transaction throws Too many SOQL queries: 101 and the whole insert rolls back, including the 100 Cases that "worked".
  2. The insert runs once per record. Even if you fixed the query, 151 Cases would hit the 150 DML statement limit.
  3. Downstream automation multiplies. Each single-record insert t fires any Task triggers and record-triggered flows separately, so their queries also stack up against the same limits.
  4. The code assumes one Account per Case lookup. If the Account was deleted between the save and the query, the single-row assignment throws List has no rows for assignment to SObject.

After: one query, one Map, one DML statement

The fix has three steps that you will reuse in almost every trigger:

  1. Loop once to collect the Ids you need into a Set<Id>.
  2. Run one SOQL query with WHERE Id IN :ids and load the results into a Map<Id, SObject>.
  3. Loop again to build a List of records to save, then call DML once on the whole list.

Put the logic in a handler class and keep the trigger to one line. That makes the code testable and keeps you at one trigger per object.

trigger CaseTrigger on Case (after insert) {
    CaseTriggerHandler.createReviewTasks(Trigger.new);
}
public with sharing class CaseTriggerHandler {

    public static void createReviewTasks(List<Case> newCases) {
        // 1. Collect the Account Ids
        Set<Id> accountIds = new Set<Id>();
        for (Case c : newCases) {
            if (c.AccountId != null) {
                accountIds.add(c.AccountId);
            }
        }

        if (accountIds.isEmpty()) {
            return;
        }

        // 2. One query, results keyed by Id
        Map<Id, Account> accountsById = new Map<Id, Account>([
            SELECT Id, OwnerId
            FROM Account
            WHERE Id IN :accountIds
        ]);

        // 3. Build every Task in memory
        List<Task> tasksToInsert = new List<Task>();
        for (Case c : newCases) {
            Account acc = accountsById.get(c.AccountId);
            if (acc == null) {
                continue; // no Account, or Account not visible to this user
            }
            tasksToInsert.add(new Task(
                WhatId       = c.Id,
                OwnerId      = acc.OwnerId,
                Subject      = 'Review new case ' + c.CaseNumber,
                ActivityDate = Date.today().addDays(1)
            ));
        }

        // One DML statement for the whole chunk
        if (!tasksToInsert.isEmpty()) {
            insert tasksToInsert;
        }
    }
}

Three details make this version work:

  • The Map constructor takes a query directly. new Map<Id, Account>([SELECT ...]) keys each Account by its Id, so accountsById.get(c.AccountId) is a constant-time lookup. You avoid a nested loop over Accounts, which would cost CPU time on large chunks.
  • A Set removes duplicates. If 200 Cases point at 3 Accounts, the query asks for 3 Ids.
  • get() returns null instead of throwing. A missing Account is skipped instead of crashing the transaction.

Resource use for 200 Cases:

BeforeAfter
SOQL queries200 (fails at 101)1
DML statements200 (fails at 151)1
Times Task automation fires2001 (for a list of 200)
Result on a 200-record importFull rollbackAll 200 Tasks created

Before triggers: skip the DML entirely

If you are changing fields on the records that fired the trigger, use a before trigger and edit Trigger.new directly. Salesforce saves those changes for you, so you don't need DML at all, and you can't hit the DML limit.

trigger ContactTrigger on Contact (before insert) {
    Set<Id> accountIds = new Set<Id>();
    for (Contact con : Trigger.new) {
        if (con.AccountId != null && con.Phone == null) {
            accountIds.add(con.AccountId);
        }
    }

    if (!accountIds.isEmpty()) {
        Map<Id, Account> accountsById = new Map<Id, Account>([
            SELECT Id, Phone FROM Account WHERE Id IN :accountIds
        ]);

        for (Contact con : Trigger.new) {
            Account acc = accountsById.get(con.AccountId);
            if (acc != null && con.Phone == null) {
                con.Phone = acc.Phone; // no update statement needed
            }
        }
    }
}

A common mistake is to write an after trigger that queries the same records and calls update on them. That costs an extra query and an extra DML statement, and it fires the trigger again, which opens the door to recursion.

You want to...UseDML needed?
Set or default fields on the triggering recordsbefore insert / before updateNo
Validate and block a save with addError()beforeNo
Create or update related recordsafterYes, one statement per object
Use the new record's Id or auto-numberafterYes, on the related records

Bulkifying update triggers: only process records that changed

Update triggers fire for every edit, including edits that have nothing to do with your logic. Compare Trigger.new with Trigger.oldMap and collect only the records whose relevant fields changed. The query stays small, and an unrelated edit to 200 records doesn't trigger any work.

public static void handleOwnerChange(List<Account> newList, Map<Id, Account> oldMap) {
    Set<Id> changedAccountIds = new Set<Id>();
    for (Account acc : newList) {
        if (acc.OwnerId != oldMap.get(acc.Id).OwnerId) {
            changedAccountIds.add(acc.Id);
        }
    }
    if (changedAccountIds.isEmpty()) {
        return;
    }

    List<Contact> contactsToUpdate = new List<Contact>();
    for (Contact con : [
        SELECT Id, OwnerId, Account.OwnerId
        FROM Contact
        WHERE AccountId IN :changedAccountIds
    ]) {
        con.OwnerId = con.Account.OwnerId;
        contactsToUpdate.add(con);
    }
    update contactsToUpdate;
}

Notice that the query reads the parent field through a relationship (Account.OwnerId), so it doesn't need a second query for Accounts.

Anti-patterns that look bulkified but aren't

PatternWhy it failsFix
Trigger.new[0]Ignores records 2 to 200Loop over the full list
Calling a helper method per record that runs a queryThe query is still inside the loop, one level downPass the whole list to the helper
Nested loop to match child to parentO(nร—m) CPU time on large chunksMap<Id, SObject> lookup
Query with no WHERE filter "to be safe"Hits the 50,000-row limit as data growsFilter with IN :ids
update on Trigger.new in an after triggerRead-only error, or recursion if you clone the recordsUse a before trigger
Database.insert in a loop with allOrNone=falseStill one DML statement per callBuild a list, call it once

Test class: prove it with 250 records

A test that inserts one record gets you code coverage and proves nothing about bulk behavior. Insert more than 200 records so the trigger runs at least twice in one transaction (200 + 50). That covers the per-chunk logic and confirms the limits hold across chunks.

@IsTest
private class CaseTriggerHandlerTest {

    @TestSetup
    static void setup() {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < 5; i++) {
            accounts.add(new Account(Name = 'Bulk Test Account ' + i));
        }
        insert accounts;
    }

    @IsTest
    static void createsOneTaskPerCaseForBulkInsert() {
        List<Account> accounts = [SELECT Id, OwnerId FROM Account];

        List<Case> cases = new List<Case>();
        for (Integer i = 0; i < 250; i++) {
            cases.add(new Case(
                Subject   = 'Bulk case ' + i,
                Status    = 'New',
                Origin    = 'Web',
                AccountId = accounts[Math.mod(i, accounts.size())].Id
            ));
        }

        Test.startTest();
        insert cases;
        Integer queriesUsed = Limits.getQueries();
        Test.stopTest();

        Integer taskCount = [SELECT COUNT() FROM Task WHERE WhatId IN :cases];
        Assert.areEqual(250, taskCount, 'Expected one review Task per Case');

        // 250 records = 2 trigger chunks = 2 queries from this handler.
        // Raise the threshold if other Case automation in your org runs queries.
        Assert.isTrue(queriesUsed <= 2,
            'Handler should run one query per chunk, but used ' + queriesUsed);
    }

    @IsTest
    static void skipsCasesWithoutAccount() {
        List<Case> cases = new List<Case>();
        for (Integer i = 0; i < 200; i++) {
            cases.add(new Case(Subject = 'No account ' + i, Status = 'New', Origin = 'Web'));
        }

        Test.startTest();
        insert cases;
        Test.stopTest();

        Assert.areEqual(0, [SELECT COUNT() FROM Task WHERE WhatId IN :cases],
            'No Tasks should be created when Case has no Account');
    }
}

What this test does:

  • Test.startTest() gives the code under test a fresh set of governor limits, so setup queries don't count against the trigger.
  • Limits.getQueries() measures the real query count inside that fresh context. The assertion catches anyone who later puts a query back inside the loop.
  • The negative test inserts 200 records with no Account to confirm the early exit and null checks hold at volume.
  • It uses the Assert class (Assert.areEqual, Assert.isTrue), which reads more clearly than the older System.assertEquals.

If you run the "before" trigger against this test, it fails with Too many SOQL queries: 101. That's the result you want to see before you refactor. For more on writing tests that check behavior, not only coverage, read Apex Test Classes: Beyond 75% Code Coverage.

Where Salesforce Casts fits

If you're comfortable with the pattern above but your org has five triggers per object and logic scattered across all of them, the free Apex Triggers Framework 101 course (8 episodes, about half an hour) shows how to set up one trigger and one handler per object. The Apex Test Fest course covers async tests, System.runAs, the Assert class and callout mocks, which is where bulk tests usually get harder.

Teja, a former engineer at Salesforce.com, teaches every course. He builds the code live in a real org, line by line, and each course comes with a GitHub repo. Every plan unlocks every course. If you're still learning SOQL and collections, start with the Apex learning path.

FAQ

Does bulkification matter if my users only edit one record at a time?

Yes. Data Loader, API integrations, mass edits from list views, Flows and other triggers all send records in batches, even if your users never do. A trigger that only works for one record will fail during the first data import or integration sync, and the whole batch rolls back.

Is 200 the maximum number of records I can insert at once?

No. 200 is the chunk size Salesforce uses when it calls your trigger. An Apex insert of 1,000 records runs the trigger five times, and all five runs share the same transaction limits. That's why one query per chunk is safe and one query per record is not.

Do I always need a Map, or is a List enough?

Use a Set<Id> to collect Ids and a Map<Id, SObject> whenever you need to find a related record by its Id. A List is the right type for the records you send to DML. Searching a List inside a loop works for small data, but it costs CPU time that a Map lookup avoids.

Does 75% code coverage prove my trigger is bulk-safe?

No. Coverage only shows which lines ran, and a single-record test can cover every line of a trigger that breaks at record 101. Insert more than 200 records in your test and assert both the outcome and the query count.

Should the logic live in the trigger or in a class?

Put it in a handler class and keep one trigger per object. Salesforce doesn't guarantee the order in which multiple triggers on the same object run. A handler class also lets you call the logic directly in tests and reuse it from batch jobs.

Can I call a future method or queueable from a trigger to avoid limits?

You can, but call it once per chunk with a list of Ids, never once per record. Async Apex has its own limits on how many jobs one transaction can enqueue, so moving the loop into async code doesn't fix it.

Next step

Open your busiest object's trigger, search for [SELECT and insert/update inside any for loop, and write the 250-record test above against it before you change any code. If you want to see the one-trigger-per-object pattern built from scratch, start the free Apex Triggers Framework 101 course.


Notes for you:

  • Limit numbers aren't verified yet. My web search failed, so the figures in the limits table come from Salesforce's documented values as I know them. Please check them against the current "Execution Governors and Limits" page before you publish.
  • Missing pages for the brief. The brief asked for links to a SOQL tutorial and to governor limits content, but neither is in your page list. I used the bulkification blog post and /learn/apex instead. If those pages exist, swap them in.
  • Company name. I used "Salesforce Casts" (from your website) rather than "Salesforce Casrs".

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion โ€” one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts