One of the biggest mistakes beginners make in Apex is writing triggers that only work for a single record. But Salesforce never guarantees that.
Records can come in bulk — from UI, Data Loader, APIs, or integrations. If your code isn’t built for that, it will break or hit governor limits.
Bulkification simply means writing code that can handle multiple records at once instead of one at a time.
trigger AccountTrigger on Account (after insert) {
for (Account acc : Trigger.new) {
Contact c = new Contact(
LastName = acc.Name,
AccountId = acc.Id
);
insert c; // ❌ DML inside loop
}
}
This will fail when multiple records are processed because it performs DML inside a loop.
trigger AccountTrigger on Account (after insert) {
List<Contact> contacts = new List<Contact>();
for (Account acc : Trigger.new) {
contacts.add(new Contact(
LastName = acc.Name,
AccountId = acc.Id
));
}
insert contacts; // ✅ Single DML
}
Here, we collect all records first and perform a single DML operation.
Salesforce has strict governor limits. If your code is not bulkified, it will work in testing but fail in real scenarios.
Always write your trigger as if it will handle 200 records at once.
Do this right, and your code becomes scalable, stable, and production-ready.
← Back to Apex