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 ..

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

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