Sub topic 1
A save is one transaction
Prerequisites
This chapter assumes you can:
- Read and write a simple Apex trigger.
- Work with Salesforce objects, fields, and records.
- Recognize validation rules and Flow as declarative automation.
- Use DML operations: insert, update, and delete.
What a transaction is
A transaction is a group of database changes that succeed or fail together. When a user, an API call, or Apex saves a record, Salesforce wraps the whole save in one transaction. Every trigger, flow, and rule that runs because of that save runs inside the same transaction.
The transaction opens when the save starts. Nothing becomes permanent until the end. If any step throws an unhandled error, Salesforce rolls back every change made in the transaction, including changes made by other automation.
Why the order matters
Salesforce runs automation in a fixed sequence. Your logic sees different data depending on where it sits in that sequence. For example, a before trigger can change field values without DML, but the record has no Id yet on insert. An after trigger can read the Id, but it cannot change Trigger.new records.
Seeing the shared transaction
The trigger below runs after an account is inserted. It creates a Task in the same transaction.
trigger AccountFollowUp on Account (after insert) {
List<Task> tasks = new List<Task>();
for (Account a : Trigger.new) {
tasks.add(new Task(Subject = 'Follow up', WhatId = a.Id));
}
insert tasks;
}The Task insert is part of the Account save. If the Task insert fails, for example because of a validation rule on Task, the Account insert is rolled back too. The user sees an error and neither record exists.
The trigger also builds one list and inserts it once. It does not run DML inside the loop. This matters because the whole transaction shares governor limits, which are the per-transaction caps on resources such as DML statements and SOQL queries.
Key points to carry forward
- A single save can run many pieces of automation, but they share one transaction.
- Records saved earlier in the transaction are visible to later steps, but they are not committed yet.
- An unhandled error at any step undoes the whole transaction.
- Governor limits apply to the whole transaction, not to each trigger or flow separately.
The following chapters walk through each step in order, starting with how Salesforce loads the record and applies the new values.
Exercise
An after insert trigger on Account inserts a Task. The Task insert fails because of a validation rule on Task. Does the Account still exist after the transaction ends, and why?
Show answer
No. The Account insert and the Task insert are in the same transaction. The unhandled error rolls back all changes in it, so the Account is not saved.