Skip to content
Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
DictionaryTTrigger
DevelopmentIntermediate

Trigger

An Apex trigger is a block of Apex code that runs automatically when records on a Salesforce object are changed through a data manipulation language (DML) event.

§ 01

Definition

An Apex trigger is a block of Apex code that runs automatically when records on a Salesforce object are changed through a data manipulation language (DML) event. Those events are insert, update, delete, undelete, merge, and upsert. A trigger is tied to one object, and it can run before the database write, after the write, or both.

You write triggers when declarative tools cannot do the job and you need code that fires on every change to a record. Common uses are validating data, updating related records, and calling out to other systems. Triggers run for every save path, whether the record comes from the UI, an import, the API, or another piece of automation.

§ 02

How Apex triggers fire and behave

Before and after: two timings, two jobs

Every trigger declares one or more events, and each event has a timing. Before triggers run while the record is still in memory and not yet saved. After triggers run once the record is written to the database, though the transaction is not committed yet. The timing decides what you can do. Use a before trigger to validate or change field values on the record that is being saved. You edit Trigger.new directly, and the platform persists those edits without a second DML call. Use an after trigger when you need values the system sets during save, such as the record Id on an insert, or when you update other records that reference this one. In an after context the records in Trigger.new are read only, so you cannot change them in place. A single trigger can handle several events at once, for example before insert, before update, after insert, after update. You branch on the context inside the body. Mixing both timings in one trigger is fine, but each branch should do work that suits its timing.

Context variables tell the trigger where it is

Apex exposes a set of implicit variables through the System.Trigger class so your code knows why it is running. The boolean flags isInsert, isUpdate, isDelete, isUndelete, isBefore, and isAfter let you branch on the exact event and timing. The variable operationType returns the same information as an enum value if you prefer a switch statement. The record collections carry the data. Trigger.new holds the records as they will be saved, available in insert and update events. Trigger.old holds the records as they were before the change, available in update and delete events. The map versions, Trigger.newMap and Trigger.oldMap, key those records by Id so you can look up a single record fast. Trigger.size returns the count in the current batch. Availability depends on the event. Trigger.new is not populated in a delete trigger because there is no incoming version. Trigger.old does not exist on insert. Knowing which collection is filled for which event prevents null reference errors that only surface on certain operations.

Triggers are bulk by design

Salesforce does not call a trigger once per record. It calls the trigger once per batch of up to 200 records. If an import loads 400 rows, the trigger fires twice, each time with up to 200 records in Trigger.new. Your code has to expect a collection every single time, even when a user edits one record in the UI. This is the root of the most important trigger rule: never put a SOQL query or a DML statement inside a loop. A query inside a loop that iterates 200 records issues 200 queries, and the governor limit caps you at 100 SOQL queries per transaction. The same applies to DML, capped at 150 statements per transaction. The fix is to work with sets and maps. Gather the Ids you need into a Set, run one SOQL query against that Set, store the results in a Map keyed by Id, then loop through Trigger.new and read from the Map. One query serves all 200 records. This bulk-safe shape keeps you under the limits whether the batch is one record or two hundred.

Where triggers sit in the order of execution

When a record saves, the platform runs a fixed sequence, and triggers occupy two known slots in it. First the system runs format and required-field validation. Then before triggers fire. After before triggers, the platform runs custom validation rules and duplicate rules. Then it saves the record to the database without committing. After triggers fire next, once the row exists but before the change is final. Following after triggers come assignment rules, auto-response rules, workflow rules, and record-triggered flows configured to run after save. If a workflow field update changes the record, the before and after update triggers run a second time on that record. Later steps include roll-up summary recalculation and, at the very end, the commit. This ordering has practical consequences. A before trigger runs ahead of validation rules, so a value you set there is what the validation rule checks. An after trigger sees the saved record but runs before most other automation, which is why it is the right place to create or update related records that depend on this one existing.

The trigger handler pattern and recursion

A common failure mode is several triggers on the same object. They run in an order you cannot control, and they compete to enforce logic. The widely used answer is one trigger per object that contains no business logic. The trigger simply calls a separate Apex class, the handler, and passes the context to it. The handler holds the real work in clear methods such as beforeInsert and afterUpdate. This makes the logic easier to read, easier to unit test, and easy to switch off when needed. Because there is one trigger, the order of operations on that object is predictable. Recursion is the other classic trap. A trigger that updates records can cause itself to fire again, and that loop can blow past limits or run logic twice. The standard guard is a static boolean variable in a class. The trigger checks the flag, sets it to true on first run, and skips the body if it is already true. Static variables hold their value for the life of one transaction, which is exactly the scope you want for blocking re-entry.

Triggers versus record-triggered flows

Triggers are no longer the only way to run logic on a record change. Record-triggered flows do similar work without code, and Salesforce now positions flows as the first option for many automations. A flow can run before or after save, much like a trigger, and admins can build one without an Apex deployment. Triggers still earn their place when the logic is complex, needs precise bulk control, requires callouts handled a specific way, or has to do things flows cannot express cleanly. Some teams run both, with flows handling straightforward updates and triggers handling the hard cases. The order of execution interleaves them, so you should know which tool owns which behavior to avoid conflicts. A practical guideline many architects use: reach for a record-triggered flow first, and drop to an Apex trigger when the flow cannot meet the requirement or the logic is too involved to maintain declaratively. Whichever you choose, keep one object's automation easy to trace, because mixing several flows and triggers on the same object without a plan creates the same unpredictable behavior that the handler pattern was meant to solve.

§ 03

How to create an Apex trigger

You create an Apex trigger in a sandbox or scratch org, then deploy it to production with test coverage. The simplest way to start is the Developer Console, which scaffolds the trigger for you on the object and events you pick.

  1. Open the Developer Console

    From the Setup gear menu, choose Developer Console. Go to File, then New, then Apex Trigger. This is the quickest place to author and save a trigger in a sandbox.

  2. Name the trigger and pick the object

    Enter a clear name such as AccountTrigger, then select the sObject it runs on, for example Account. A trigger is bound to exactly one object and cannot span several.

  3. Declare the events

    In the generated trigger header, list the events inside parentheses, such as (before insert, before update, after insert). Each event sets a timing and a DML operation the trigger responds to.

  4. Branch and call a handler

    Inside the body, check the context with flags like Trigger.isBefore and Trigger.isInsert, then call a handler class method. Keep business logic in the handler, not in the trigger.

  5. Write tests and deploy

    Create a test class that inserts and updates 200 records to prove the trigger is bulk safe. Production deployment requires at least 75 percent code coverage across your Apex.

Trigger namerequired

A unique API name for the trigger, used as the file name and in metadata. Pick a convention like ObjectTrigger so each object has one obvious trigger.

sObjectrequired

The single object the trigger runs on. The trigger fires only for DML on this object, and you cannot change the object after creation without recreating the trigger.

Eventsrequired

One or more of before insert, before update, before delete, after insert, after update, after delete, after undelete. At least one event is required for the trigger to do anything.

Gotchas
  • You cannot deploy a trigger straight into a production org by editing it there. Author it in a sandbox or scratch org, then deploy with tests.
  • Trigger.new is read only in after contexts. To change field values on the record being saved, do it in a before trigger instead.
  • There is no after merge or after upsert event. A merge fires delete and update triggers, and an upsert fires insert and update triggers.

Prefer this walkthrough as its own page? How to Trigger in Salesforce, step by step

§

Trust & references

Sources

Cross-checked against the following references.

Official documentation

Straight from the source - Salesforce's reference material on Trigger.

Was this entry helpful?
Help us write better definitions. Quick reactions or detailed edit suggestions.

About the Author

Dipojjal Chakrabarti is a B2C Solution Architect with 29 Salesforce certifications and over 13 years in the Salesforce ecosystem. He runs salesforcedictionary.com to help admins, developers, architects, and cert/interview candidates sharpen their fundamentals. More about Dipojjal.

§

Test your knowledge

Q1. When does an Apex Trigger execute relative to a DML event on its object?

Q2. Why does the Trigger Handler pattern recommend one Trigger per object delegating to a class?

Q3. What is required before Apex including a Trigger can be deployed to a Salesforce production org?

§

Discussion

Loading…

Loading discussion…