Sub topic 7
Fixing Mixed DML Errors
This chapter assumes you can write Apex classes and static methods, run SOQL and DML, and have declared a basic @future method. It covers why the mixed DML error happens, how a future method fixes it, and the cases where it does not.
What the error is
Salesforce stores two kinds of objects, and it does not let you change both in one transaction.
- Setup objects define configuration and access. Examples:
User,UserRole,Group,GroupMember,PermissionSet,PermissionSetAssignment,QueueSObject, andProfile-related records. - Non-setup objects hold business data. Examples:
Account,Contact,Opportunity, and your custom objects.
If one transaction runs DML on both kinds, Apex throws a System.DmlException with this message:
MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)The order does not matter. Setup then non-setup fails, and so does non-setup then setup. The reason is that changes to setup objects can alter sharing and access, which can affect the records in the same transaction.
A failing example
public class OnboardingService {
public static void createAccountAndRole() {
insert new Account(Name = 'Acme');
insert new UserRole(Name = 'Acme Manager', DeveloperName = 'Acme_Manager');
}
}Running OnboardingService.createAccountAndRole() throws the mixed DML error on the second insert. The Account insert counts as non-setup DML. Once it has run, the UserRole insert is refused.
How a future method fixes it
A future method runs in its own transaction, after the calling transaction finishes. The two transactions each see only one kind of object, so the rule is not broken.
Move the setup object DML into a future method:
public class SetupDmlHelper {
@future
public static void createRole(String roleName, String developerName) {
insert new UserRole(Name = roleName, DeveloperName = developerName);
}
}Then call it from the code that changes the non-setup object:
public class OnboardingService {
public static void createAccountAndRole() {
insert new Account(Name = 'Acme');
SetupDmlHelper.createRole('Acme Manager', 'Acme_Manager');
}
}The Account insert happens in the original transaction. The UserRole insert is queued and runs later in a separate transaction.
The future method takes two String values rather than a UserRole record. Future methods accept only primitives, arrays of primitives, and collections of primitives. They cannot take sObjects. Build the record inside the method, as the example does.
Common scenarios
Mixed DML shows up in a few predictable places.
| Scenario | Why it fails | Fix |
|---|---|---|
| Creating a `User` and a `Contact` in one method | `User` is a setup object, `Contact` is not | Put the `User` DML in a future method |
| Assigning a permission set after updating an `Account` | `PermissionSetAssignment` is a setup object | Move the assignment into a future method |
| Adding a user to a public group in a trigger on a business object | `GroupMember` is a setup object | Call a future method from the trigger |
| Inserting test data for a `User` and an `Account` | Both are in the same test transaction | Use `System.runAs()` or move one into a future method (see below) |
The exception: User DML in some cases
Some fields on User can be updated alongside non-setup objects. For example, updating User fields such as LastName or Email is generally allowed with non-setup DML, while changing IsActive, UserRoleId, or ProfileId is treated as a setup change. Do not rely on memory here. If you are unsure whether a particular field triggers the error, test it in a sandbox.
A realistic example: assign a permission set after a business change
Suppose a trigger on Opportunity must give the owner a permission set when the opportunity closes as won. The assignment is setup DML, and the trigger is already in a non-setup transaction.
public class PermissionAssigner {
@future
public static void assign(Set<Id> userIds, String permSetName) {
PermissionSet ps = [
SELECT Id FROM PermissionSet WHERE Name = :permSetName LIMIT 1
];
Set<Id> alreadyAssigned = new Set<Id>();
for (PermissionSetAssignment existing : [
SELECT AssigneeId FROM PermissionSetAssignment
WHERE PermissionSetId = :ps.Id AND AssigneeId IN :userIds
]) {
alreadyAssigned.add(existing.AssigneeId);
}
List<PermissionSetAssignment> toInsert = new List<PermissionSetAssignment>();
for (Id userId : userIds) {
if (!alreadyAssigned.contains(userId)) {
toInsert.add(new PermissionSetAssignment(
AssigneeId = userId,
PermissionSetId = ps.Id
));
}
}
insert toInsert;
}
}Three design choices in this method:
- It takes a
Set<Id>, which is a collection of primitives, so it is a legal parameter. - It queries for existing assignments first. Inserting a duplicate
PermissionSetAssignmentthrows an error, and because the future method runs later, the data may have changed since it was queued. - It does all its work in bulk. One call handles every user in the set.
The trigger that calls it:
trigger OpportunityTrigger on Opportunity (after update) {
Set<Id> ownerIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.IsWon && !oldOpp.IsWon) {
ownerIds.add(opp.OwnerId);
}
}
if (!ownerIds.isEmpty() && !System.isFuture() && !System.isBatch()) {
PermissionAssigner.assign(ownerIds, 'Closed_Won_Access');
}
}Closed_Won_Access is a placeholder. Use the API name of a permission set that exists in your org.
Limits and trade-offs
The fix is not free. Keep these points in mind.
- No guaranteed timing. The setup change happens after the original transaction commits, not during it. Code that runs right after the call cannot assume the role, group, or permission is in place.
- No rollback link. If the original transaction rolls back, the future call is discarded because the job is only queued at commit. If the future method fails, the first transaction has already committed and is not undone.
- Errors are not returned. The caller cannot catch an exception thrown inside a future method. Log failures or write them to a custom object so someone can see them.
- Limits still apply. A transaction can make at most 50 future calls, and a future method has its own governor limits for the new transaction. See the limits chapter for details.
- Cannot chain. A future method cannot call another future method, so you cannot split setup DML across several future hops.
Other ways to avoid the error
A future method is one option. Know the alternatives so you can choose.
- Queueable Apex. Also runs in a separate transaction, accepts sObjects and custom types, and lets you chain jobs. It is often the better choice for new code. The final chapter compares the options.
- Reordering. Sometimes the two operations can live in different transactions already, for example in two separate trigger events or two user actions.
System.runAs()in tests. In test code, wrapping the setup DML in aSystem.runAs()block gives it its own context, so it does not conflict with earlier non-setup DML.
Mixed DML in tests
Tests hit this error often because they create a User and some business records together. The standard fix is to run the non-setup or setup part under System.runAs():
@isTest
private class MixedDmlTest {
@isTest
static void createUserAndAccount() {
User admin = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
System.runAs(admin) {
UserRole r = new UserRole(Name = 'Test Role', DeveloperName = 'Test_Role');
insert r;
}
Account a = new Account(Name = 'Test Account');
insert a;
System.assertEquals(1, [SELECT COUNT() FROM Account WHERE Id = :a.Id]);
}
}Here the role insert happens inside runAs, so the later Account insert does not conflict with it.
If you test a future method that does setup DML, call it between Test.startTest() and Test.stopTest(). That forces the queued work to run before your assertions, as covered in the testing chapter.
Common mistakes
- Passing an sObject.
@future public static void f(UserRole r)does not compile. Pass the values or IDs and build the record inside. - Calling the future method per record in a loop. This hits the 50-call limit fast. Collect IDs first and call once.
- Calling from another future method or from Batch Apex
execute. This is not allowed. Check withSystem.isFuture()andSystem.isBatch(), or use a Queueable instead. - Assuming the change is visible immediately. Reading the role back in the same transaction will not find it.
- Swallowing errors. An unhandled exception in the future method shows up only in the job monitor and debug logs.
Summary of the approach
- Identify which statement touches a setup object.
- Move that statement into a static
@futuremethod that takes IDs or primitives. - Build or re-query records inside the method.
- Call the method once per transaction with a collection.
- Guard against calls from contexts where future methods are not allowed.
- Handle and log errors inside the method.
- Test with
Test.startTest()andTest.stopTest().
Exercise
A trigger on Contact must add the contact's owner to a public group after insert. The trigger code calls insert new GroupMember(GroupId = g.Id, UserOrGroupId = c.OwnerId); directly and fails with MIXEDDMLOPERATION. Explain why it fails and describe how you would fix it, including what the future method should accept.
Show answer
GroupMember is a setup object, and the trigger runs in a transaction that is already changing Contact, a non-setup object. Apex does not allow both kinds of DML in one transaction. Fix it by moving the GroupMember insert into a static void @future method that accepts a Set<Id> of owner IDs (and a group ID or group name as a primitive). Inside the method, query for existing memberships to avoid duplicates, build the GroupMember records, and insert them in one DML statement. In the trigger, collect owner IDs into a set, then call the method once, guarded by !System.isFuture() && !System.isBatch().
Exercise
You wrote @future public static void createRole(UserRole r) { insert r; } and it will not save. What is wrong, and how do you rewrite it?
Show answer
Future methods cannot take sObjects as parameters. Only primitives, arrays of primitives, and collections of primitives are allowed. Change the signature to accept values, for example createRole(String roleName, String developerName), and build the UserRole inside the method with insert new UserRole(Name = roleName, DeveloperName = developerName);.