Sub topic 1
What an Apex Trigger Is and When It Runs
Prerequisites
This chapter assumes you already know:
- Basic Apex syntax, including classes, methods, and control flow.
- The Salesforce data model and how sObjects such as Account, Contact, and Opportunity relate.
- Basic SOQL queries and DML statements (
insert,update,delete,undelete). - That records can be inserted, updated, deleted, and undeleted, and that each of these actions can fire logic.
You do not need to have written a trigger before. This chapter builds the working model that the rest of the tutorial relies on.
What a trigger is
An Apex trigger is a block of Apex code that Salesforce runs automatically before or after a record is saved to the database. You attach a trigger to one sObject type, such as Contact. You then choose the events that fire it, such as before insert or after update.
A trigger is different from a method you call yourself. Nothing in your code invokes it. The platform runs it whenever a matching DML operation touches that object. That operation can come from the UI, an API call, a data load, a Flow, or other Apex code. Your trigger therefore has to behave correctly no matter where the change came from.
Here is the smallest useful trigger:
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
if (c.Description == null) {
c.Description = 'Created on ' + Date.today().format();
}
}
}Anatomy of a trigger
A trigger declaration has four parts:
- The keyword
triggerand a name, such asContactTrigger. - The keyword
onand the sObject type, such asContact. - A parenthesized, comma-separated list of events.
- A body in braces.
trigger OpportunityTrigger on Opportunity (
before insert, before update,
after insert, after update
) {
// body
}The event list combines a timing (before or after) with an operation. The supported events are:
| Event | Fires |
|---|---|
| `before insert` | Before new records are written to the database |
| `before update` | Before changes to existing records are written |
| `before delete` | Before records are deleted |
| `after insert` | After new records are saved and have IDs |
| `after update` | After changes are saved |
| `after delete` | After records are deleted |
| `after undelete` | After records are restored from the Recycle Bin |
There is no before undelete. Also, there is no event for a merge or an upsert as such. An upsert fires insert or update events for each record, depending on whether it matched an existing record.
You can put several events in one trigger, as the example above does. The trigger then runs once for each matching event, and the body has to work out which event is active. The next chapter covers the context variables that tell you.
When a trigger runs
A trigger runs inside a transaction. A transaction is a set of operations that either all commit or all roll back. The trigger's work shares that transaction with the DML that fired it.
The order of events for a single save looks like this:
This is a simplified view. The full Salesforce order of execution also includes flows, duplicate rules, assignment rules, and workflow field updates. Some of those can cause your trigger to run a second time within the same transaction. The recursion chapter returns to that.
Three points follow from the diagram:
- Before triggers run early, before the record is written. Changes you make to the new records in memory are saved with them, with no extra DML.
- After triggers run once the record exists and has an ID. Records you create that point back to it need that ID.
- An uncaught exception anywhere in the transaction rolls back everything, including work the trigger already did.
Triggers receive a list
A trigger does not run once per record. It runs once per batch, and the batch can hold up to 200 records. This is why Trigger.new is a List, even when a user saves a single record in the UI.
Where the batches come from:
- A data load through the Bulk API splits records into chunks of up to 200, and the trigger fires once for each chunk.
- A single
insertof a list of 500 records from Apex makes the platform call the trigger in chunks of 200 and then 200 and then 100. All the chunks belong to one transaction and share the same limits. - A single record saved in the UI produces a batch of one.
Code written as if there were only one record will pass a manual test in the UI. It will then fail when a data load sends 200.
Why this matters: governor limits
Salesforce runs many customers on shared infrastructure. To keep one customer's code from using all the resources, it enforces governor limits. These limits apply per transaction. The ones that matter most for triggers are:
| Limit | Synchronous transaction |
|---|---|
| SOQL queries issued | 100 |
| Records returned by SOQL | 50,000 |
| DML statements issued | 150 |
| Records processed by DML | 10,000 |
| CPU time | 10,000 ms |
| Heap size | 6 MB |
Check the current Apex Developer Guide for the exact values, since Salesforce can change them, and asynchronous transactions have higher limits for some of these. When a transaction goes over a limit, Salesforce throws a System.LimitException. You cannot catch it, and the whole transaction rolls back.
The two limits you will hit first are 100 queries and 150 DML statements. A trigger that runs a query per record gets through a batch of 99 and then fails on a batch of 101 or more.
An example that breaks at scale
This trigger works when you save one Contact. It fails on a larger batch.
trigger ContactTrigger on Contact (before insert) {
for (Contact c : Trigger.new) {
// Anti-pattern: one SOQL query per record
Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
if (a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}There are two problems:
- The query sits inside the loop, so a batch of 101 or more contacts exceeds the limit of 100 SOQL queries and throws a
System.LimitException. - When
AccountIdis null, the query returns no rows. Assigning that empty result to a singleAccountvariable throws aSystem.QueryException. This fails even on a batch of one.
Both problems have one fix: query once, outside the loop, and look the results up in memory. The collections chapters show how.
trigger ContactTrigger on Contact (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account a = accountsById.get(c.AccountId);
if (a != null && a.Industry == 'Banking') {
c.Description = 'Banking contact';
}
}
}This version issues one query for any batch size. Treat it as a preview. The details come later in this tutorial.
Common mistakes
- Assuming one record. Reading
Trigger.new[0]ignores the other 199 records in the batch. - Assuming the trigger only fires from the UI. Integrations, Flows, and batch jobs all fire it, and they often send large batches.
- Testing with one record. A test that inserts one record will not show a limit problem. A later chapter covers testing with 200.
- Several triggers on one object. Salesforce does not guarantee the order in which multiple triggers on the same object and event run. Using one trigger per object keeps the order under your control.
- Putting all logic in the trigger body. It becomes hard to test and reuse. The handler pattern chapter addresses this.
Summary of the working model
- A trigger is code that Salesforce runs on its own when a record is inserted, updated, deleted, or undeleted.
- It runs in the same transaction as the DML that fired it, so an error rolls back the whole transaction.
- It receives a list of up to 200 records, and all batches in one transaction share one set of governor limits.
- Code that queries or writes once per record will eventually exceed those limits.
Exercise
A user loads 450 Contacts in one insert statement from Apex, and your trigger contains a SOQL query inside a for loop over Trigger.new. How many times does the trigger fire, and what happens?
Show answer
The platform splits the 450 records into chunks of 200, 200, and 50, so the trigger fires three times in the same transaction. The loop runs the query once per record, so the transaction reaches the 100-query limit part-way through the first chunk. Salesforce throws an uncatchable System.LimitException, and the whole transaction rolls back, including any records already processed.
Exercise
Why can a single trigger declared with before insert, after update not assume that every run sees new records with IDs?
Show answer
The trigger runs once for each event. On before insert, the records have no ID yet, because they have not been written to the database. On after update, the records already exist and have IDs. The body must check which event is active before using the ID.