Sub topic 1
What an Apex Transaction Is
An Apex transaction is the set of operations that run from one entry point until the platform either saves all the database changes or discards them. This chapter covers the working model. Later chapters cover savepoints, partial success, and testing.
Prerequisites
This chapter assumes you can:
- Read and write basic Apex: classes, methods, and collections.
- Run DML statements such as
insertandupdateon sObjects. - Use
try/catchand recognizeDmlException. - Name the common governor limits, such as the SOQL query limit and the DML statement limit.
You can run every example in the Developer Console's Execute Anonymous window. Use a sandbox or a Developer Edition org.
The Idea: A Unit of Work
Apex runs on a multitenant platform with a relational database underneath. A transaction groups several database changes into one unit of work. The platform guarantees that the unit ends in one of two ways:
- Commit: every change is saved permanently.
- Rollback: every change is discarded, as if the code had never run.
Without this guarantee, an error halfway through a method could leave you with an Account but no Contact, or an Opportunity without its line items. Transactions prevent that half-finished state.
Apex does not ask you to write BEGIN or COMMIT. The platform opens the transaction when execution starts and commits when execution finishes without an unhandled error. You influence the outcome through how you handle errors.
What Belongs to the Transaction
A transaction is larger than your own method. It includes everything that runs as a result of the entry point, in the same execution context:
| Part of the transaction | Example |
|---|---|
| Your Apex code | The method that calls `insert` |
| Apex triggers fired by DML | An `after insert` trigger on Account |
| Other Apex called from those triggers | Handler classes, helper methods |
| Declarative automation that runs synchronously | Record-triggered flows, validation rules, workflow field updates |
| Other DML caused by any of the above | A trigger that inserts a Task |
The rule has consequences. If an insert on Account fires a trigger, and that trigger throws an unhandled exception, the exception reaches your original entry point. The transaction fails as a whole, and the original Account is rolled back too.
Seeing a Transaction in Action
The following snippet inserts an Account, proves the insert is visible inside the transaction, and then fails on purpose.
Account a = new Account(Name = 'Txn Demo');
insert a;
System.debug('Id after insert: ' + a.Id);
Integer inside = [SELECT COUNT() FROM Account WHERE Name = 'Txn Demo'];
System.debug('Rows visible inside the transaction: ' + inside);
throw new IllegalStateException('Stop before the transaction ends');Run it, then run this query in a separate execution:
System.debug([SELECT COUNT() FROM Account WHERE Name = 'Txn Demo']);The second run prints 0. Three things happened in the first run:
- The
insertassigned anIdtoa. The database accepted the row, but it was not yet permanent. - The SOQL query inside the same transaction found the row. Code in a transaction sees its own uncommitted changes.
- The unhandled exception ended the execution, so the platform rolled the insert back.
Other users and other transactions never saw the row. Uncommitted changes are visible only to the transaction that made them.
Commit Happens at the End
A successful insert statement does not commit anything. It stages a change inside the open transaction. The commit comes once, after all of the following have finished without an unhandled error:
- Your code has run to completion.
- All triggers and synchronous automation have run.
- No governor limit has been exceeded.
This explains a behavior that surprises people. A line like insert a; can succeed, and the code can continue for several more statements, yet the record still never appears in the org. A later error can still undo it, because the commit has not happened yet.
public with sharing class OrderService {
public static void createOrderWithItems() {
Account acct = new Account(Name = 'Order Customer');
insert acct; // staged, not committed
Contact c = new Contact(LastName = 'Buyer', AccountId = acct.Id);
insert c; // staged, not committed
Integer bad = 1 / 0; // unhandled MathException: both inserts are rolled back
}
}When createOrderWithItems is called and the division fails, neither the Account nor the Contact is saved. You do not need to write any cleanup code for this case.
Governor Limits Apply Per Transaction
Governor limits are counted per transaction, not per method or per class. A few synchronous limits:
| Resource | Limit per transaction |
|---|---|
| SOQL queries | 100 |
| DML statements | 150 |
| Records processed by DML | 10,000 |
| CPU time | 10,000 ms |
| Callouts | 100 |
Because triggers and called classes share the transaction, their usage adds up. A method that issues 60 queries and fires a trigger that issues 50 more has used 110 queries, which exceeds the limit. A limit violation raises an uncatchable System.LimitException, and the transaction rolls back.
Savepoints and rollbacks also count against the DML statement limit. A later chapter covers that cost.
Row Locks and Other Users
While a transaction holds uncommitted changes to a record, the platform locks that record against changes by other transactions. Another transaction that tries to update it waits for a short time and then fails with a UNABLE_TO_LOCK_ROW error. The lock is released when your transaction commits or rolls back.
This is one practical reason to keep transactions short. Avoid doing slow work between a DML statement and the end of the transaction.
Common Misunderstandings
- "Each DML statement is its own transaction." It is not. Many DML statements in one execution share one transaction. A single statement is atomic by default, and the next chapters explain that behavior.
- "A
catchblock always rolls back." It does not. Only an unhandled exception triggers the automatic rollback. A later chapter shows what a caught exception does to earlier DML. - "An
Idmeans the record is saved." AnIdis assigned at insert time, but the row can still be discarded if the transaction rolls back. - "A trigger has its own transaction." It does not. A trigger runs inside the transaction of the DML that fired it.
What Comes Next
You now have the working model: one entry point, one transaction, one commit or one rollback, with everything in between sharing the same limits and the same fate. The next chapter lists the entry points that start a transaction, such as Execute Anonymous, triggers from the user interface, and asynchronous jobs. It also shows where each one ends.
Exercise
A method inserts an Account, then calls a helper that inserts a Contact. An after insert trigger on Contact throws an unhandled exception. Is the Account saved? Explain why.
Show answer
No. The trigger runs inside the same transaction as the Contact insert, which is also the same transaction as the Account insert. The unhandled exception propagates up to the entry point and the platform rolls back every change made in the transaction, including the Account.
Exercise
You run insert new Account(Name = 'X'); in Execute Anonymous, and the next line is a SOQL query that counts Accounts named 'X'. The query returns 1. Right after, the code throws an unhandled exception. What does a separate query find afterward, and why did the first query still return 1?
Show answer
The separate query finds 0 rows, because the unhandled exception rolled the transaction back. The first query returned 1 because code inside a transaction can see its own uncommitted changes.