Salesforce Interview Questions & Answers Book is now available!

Grab Now

Apex

Mixed DML Operation Error

Let me walk you through when do you encounter Mixed DML Operation Error and how can you fix it.

By Teja, ex-Salesforce engineer · Updated February 6, 2020 · 1 min read

There is a good chance you have come here after you had encountered Mixed DML Operation Error when you were working with a Test class.

Mixed DML Operation Error pop ups when you try to perform DML operations on both setup objects and non-setup objects in a single method.

What are setup objects

Setup objects are objects that are used to interact with the metadata. Some of them are User, UserRole, CustomField, Custom Tab and etc.

What are non-setup objects

Anything and everything that doesn't fall into the bucket of setup objects are called non-setup objects.

Why do we get mixed DML Operation Error?

In an apex method when you try to perform DML operations on both setup and non-setup objects, they don't go well and it throws Mixed DML Exception.

How can we avoid getting mixed DML Operation Error?

By using Async Apex, to be even more precise by using @future annotation.

That way, we are trying to run the business logic that’s in the apex method, in one thread and the business logic that in the @future annotated method in one thread.

This is how the apex class is going to look like ..

@isTest
public class UserAndContactTest {
    public testmethod static void testUserAndContact() {
        InsertFutureUser.insertUser();
        Contact currentContact = new Contact(
            firstName = String.valueOf(System.currentTimeMillis()),
            lastName = 'Contact');
        insert(currentContact);
    }
}

And am trying to push the business logic that is associated with setup objects in to a different method using @future annotation.

public class InsertFutureUser {
    @future
    public static void insertUser() {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
        User futureUser = new User(firstname = 'Future', lastname = 'User',
            alias = 'future', defaultgroupnotificationfrequency = 'N',
            digestfrequency = 'N', email = 'test@test.org',
            emailencodingkey = 'UTF-8', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey = 'America/Los_Angeles',
            username = 'futureuser@test.org',
            userpermissionsmarketinguser = false,
            userpermissionsofflineuser = false, userroleid = r.Id);
        insert(futureUser);
    }
}

Where will you often encounter this error?

Based on what I have seen, there is a good possibility that you will come across them in test methods.

Let's say, you have an apex method running in user mode ..

We need to insert a user record and User object is a setup object.

We also need to insert records into custom objects based on the business logic in the apex method.

Now, we are trying to perform insert operation on both setup objects and non-setup objects and it throws the error.

Other frequently encountered errors

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts