Hello Everyone, In this post, I am going to tell about MIXED_DML_OPERATION error, which is very common for any Salesforce user. In this unit, I will tell you the reason of this exception and how to avoid this error while building code logic.



After completing this unit you'll be able to: 
  • Why MIXED_DML_OPERATION error occurred?
  • How we avoid this error?
So let's begin,

Why MIXED_DML_OPERATION error occurred?

In Salesforce all the Apex classes and triggers executed synchronously so when you try to perform DML operation on setup and Non-setup objects in the same transaction, you can easily run into this error.

Setup objects are Group1, GroupMember, QueueSObject, User, UserRole, UserTerritory, Territory, etc.

Non-Setup objects are standard objects like Account or any custom object.

To avoid MIXED_DML_OPERATION error

We should perform DML operations on setup/Non-setup object records in a different transaction. If we perform DML asynchronously, we can easily avoid this error. For asynchronous operation build your logic in an apex method(in a separate apex class, not in the same trigger) which is declared with @future annotation.

Example:

  public class MyClass {
      @future
      public static void InsertUser(String uname, String al, String em, String lname) { 
          Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
          UserRole r = [SELECT Id FROM UserRole WHERE Name='COO']; 
          User u = new User(alias = al, email=em,
          emailencodingkey='UTF-8', lastname=lname,
          languagelocalekey='en_US',
          localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
          timezonesidkey='America/Los_Angeles',
          username=uname);
          insert u;
      }

  }

  trigger ContactCreation on Account(after insert) {
   List lc = new List();
   for (Account acc : Trigger.new) {
    lc.add( new contact(lastname ='MK',accountId =acc.id) );
   }
   insert lc; 
   MyClass.InsertUser('smanisheng@gmail.com', 'Manish','smanisheng@gmail.com', 'ManishMK');
  }
When the above trigger is executed both contact and user are created without any  MIXED_DML_OPERATION error.

See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.