DML and Transactions · Lesson 22 of 41
Apex Transactions, Savepoints and Mixed DML
Every request in Salesforce – a button click, an API call, a batch chunk – runs as one transaction. All its database changes are committed together at the end, or none are. Understanding where a transaction starts and ends explains rollbacks, why emails go out only after a save succeeds, and the infamous MIXED_DML_OPERATION error.
In this lesson
- What a transaction is and when it commits
- Savepoints and partial rollback
- What waits until after commit
- Mixed DML and how to avoid it
The life of a transaction
- Starta request arrives: UI save, API call, trigger, async job
- Workqueries, DML, triggers, flows – all inside the same transaction and limits
- Commitsuccess: every change is written permanently
- Or roll backan unhandled exception undoes every change
- After commitemails sent, @future and Queueable jobs start, platform events (publish after commit) delivered
All or nothing
An unhandled exception rolls back everything the transaction did – even DML statements that succeeded earlier. If you catch the exception, the earlier work stays:
// TransferService.cls
public with sharing class TransferService {
public static void moveContacts(Id fromAccountId, Id toAccountId) {
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :fromAccountId];
for (Contact c : contacts) c.AccountId = toAccountId;
update contacts;
// second step fails: the new owner account must have a phone number
Account target = [SELECT Phone FROM Account WHERE Id = :toAccountId];
if (target.Phone == null) {
throw new IllegalArgumentException('Target account needs a phone number');
}
}
}
Account a = new Account(Name = 'Old Co');
Account b = new Account(Name = 'New Co');
insert new List<Account>{ a, b };
insert new Contact(LastName = 'Rao', AccountId = a.Id);
Savepoint sp = Database.setSavepoint();
try {
TransferService.moveContacts(a.Id, b.Id);
} catch (IllegalArgumentException e) {
Database.rollback(sp); // undo the half-finished move
System.debug('Rolled back: ' + e.getMessage());
}
System.debug('Rao is still at ' + [SELECT Account.Name FROM Contact LIMIT 1].Account.Name);
Rolled back: Target account needs a phone number Rao is still at Old Co
Without the savepoint, catching the exception would have kept the contact update while reporting a failure – the worst of both worlds. Savepoints let you make a group of changes behave as one unit, even inside a larger transaction.
Savepoints in detail
Account acc = new Account(Name = 'Savepoint Demo');
insert acc;
Savepoint beforeChanges = Database.setSavepoint();
acc.Rating = 'Hot';
update acc;
insert new Contact(LastName = 'Temp', AccountId = acc.Id);
System.debug('Before rollback: rating ' + [SELECT Rating FROM Account WHERE Id = :acc.Id].Rating + ', contacts ' + [SELECT COUNT() FROM Contact]);
Database.rollback(beforeChanges);
System.debug('After rollback: rating ' + [SELECT Rating FROM Account WHERE Id = :acc.Id].Rating + ', contacts ' + [SELECT COUNT() FROM Contact]);
// the in-memory sObject still holds the old values – re-query after a rollback
System.debug('In memory: ' + acc.Rating);
System.debug('DML statements used: ' + Limits.getDmlStatements());
Before rollback: rating Hot, contacts 1 After rollback: rating null, contacts 0 In memory: Hot DML statements used: 5
- Setting a savepoint and rolling back each count as a DML statement.
- Rollback restores the database, not your variables: records keep their in-memory values (and Ids of rolled-back inserts), so re-query or reset them.
- Rolling back to a savepoint discards any savepoints set after it.
What happens after commit
Some work only makes sense if the transaction succeeds, so the platform holds it until commit: outbound emails, @future calls, enqueued Queueable jobs and Platform Events published with "publish after commit". If the transaction rolls back, none of them happen – which is exactly what you want ("don't email the customer about an order that wasn't saved"). It also means you can't see their effects later in the same transaction.
Mixed DML
Salesforce separates setup objects (User, Group, PermissionSetAssignment, UserRole…) from regular data. Changing both in one transaction throws MIXED_DML_OPERATION, because setup changes can affect sharing for everything else. There are exceptions – inserting a User without a role is allowed alongside other records – but roles, group members, permission set assignments and users with a role all trigger it. In tests, System.runAs starts a separate context for the setup work:
// MixedDmlTest.cls
@IsTest
private class MixedDmlTest {
@IsTest
static void mixedDmlFails() {
insert new UserRole(Name = 'Key Account Manager'); // setup object
try {
insert new Account(Name = 'Same transaction'); // regular object
Assert.fail('expected a mixed DML error');
} catch (DmlException e) {
Assert.areEqual(StatusCode.MIXED_DML_OPERATION, e.getDmlType(0));
}
}
@IsTest
static void runAsSeparatesTheWork() {
System.runAs(new User(Id = UserInfo.getUserId())) {
insert new UserRole(Name = 'Key Account Manager'); // setup DML in its own context
}
insert new Account(Name = 'Works fine');
Assert.areEqual(1, [SELECT COUNT() FROM Account]);
}
}
✓ MixedDmlTest.mixedDmlFails ✓ MixedDmlTest.runAsSeparatesTheWork Tests: 2 passed, 0 failed, 2 total
In production code, split the work instead: make the setup change in an @future method or a Queueable, which runs in its own transaction after the current one commits.
Practice
Try it yourself
An LWC calls an Apex method that creates an Order, then its Order Items; if an item fails, the Order should not exist. How do you code it?
Show answer
Let the exception propagate (the whole transaction rolls back) – or, if you catch it to return a friendly message, set a savepoint before inserting the Order and
Database.rollback(sp)in the catch block before throwing anAuraHandledException.A trigger on Contact assigns a permission set to a user and fails with MIXED_DML_OPERATION. What's the fix?
Show answer
Move the PermissionSetAssignment insert into an
@futuremethod or a Queueable job so it runs in a separate transaction.
Quick check
When are changes in a transaction committed?
At the end of the transaction, if no unhandled exception occurred.
Does Database.rollback reset your sObject variables?
No – only the database; re-query or reset variables yourself.
What causes MIXED_DML_OPERATION?
DML on setup objects (like User) and non-setup objects in the same transaction.
Summary
- A transaction commits everything at the end or rolls everything back.
- Use savepoints to undo a group of changes when you catch an exception.
- Emails, async jobs and after-commit events wait for a successful commit.
- Separate setup and data DML – runAs in tests, async jobs in production.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.