Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      The Power Of The Intl API: A Definitive Guide To Browser-Native Internationalization

      August 8, 2025

      This week in AI dev tools: GPT-5, Claude Opus 4.1, and more (August 8, 2025)

      August 8, 2025

      Elastic simplifies log analytics for SREs and developers with launch of Log Essentials

      August 7, 2025

      OpenAI launches GPT-5

      August 7, 2025

      3 portable power stations I travel everywhere with (and how they differ)

      August 9, 2025

      I tried Lenovo’s new rollable ThinkBook and can’t go back to regular-sized screens

      August 9, 2025

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025

      Forget Back to School Deals — Lenovo’s Clearance Sale is Where You’ll Find Amazing Discounts on Laptops, Mini PCs, and More, While Supplies Last

      August 9, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      spatie/laravel-flare

      August 9, 2025
      Recent

      spatie/laravel-flare

      August 9, 2025

      Establishing Consistent Data Foundations with Laravel’s Database Population System

      August 8, 2025

      Generate Postman Collections from Laravel Routes

      August 8, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025
      Recent

      The Creators of the Acclaimed Silent Hill 2 Remake Present a Deep Dive Into the Story of Their Newest Horror Game IP — and It’s So Bizarre and Insane That It’s Convinced Me To Put It on My Wishlist

      August 9, 2025

      Forget Back to School Deals — Lenovo’s Clearance Sale is Where You’ll Find Amazing Discounts on Laptops, Mini PCs, and More, While Supplies Last

      August 9, 2025

      The Gaming Desktop I’ve Relied on More Than Any Other Is More Powerful and Sleeker Than Ever — But Damn, It’s Expensive

      August 9, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Mastering Mixed DML Operations in Apex

    Mastering Mixed DML Operations in Apex

    June 24, 2025

    Salesforce Apex is a versatile programming language that empowers developers to automate processes, customize functionalities, and build dynamic applications. However, while working with Apex, developers often encounter a common hurdle: Mixed DML Operations. This restriction can be frustrating if not understood properly. In this blog, we’ll explore what Mixed DML Operations are, why they occur, and how to handle them effectively. By the end, you’ll have a clear understanding of how to avoid this issue and write efficient Apex code.

    What Are Mixed DML Operations?

    In Salesforce, developers use DML (Data Manipulation Language) operations to insert, update, delete, or upsert records in the database. They perform these operations on setup objects (e.g., User, Group, Group Member) and non-setup objects (e.g., Account, Contact, Custom Objects).

    A Mixed DML Operation occurs when you attempt to perform DML operations on both setup and non-setup objects within the same transaction. Salesforce applies this restriction to protect data integrity and avoid potential conflicts in the database.

    Why Does Salesforce Enforce This Restriction?

    Salesforce enforces this restriction because setup and non-setup objects reside in separate database tables. Mixing DML operations on these objects in a single transaction can lead to inconsistencies, deadlocks, or other database issues. To prevent such problems, Salesforce throws a runtime error when it detects a Mixed DML Operation.

    Example of a Mixed DML Operation

    Let’s consider a practical example to illustrate this issue. Suppose you want to create a new User and a new Account in the same transaction. Here’s how the code might look:

    Apex

    public class MixedDMLExample
    {
        public static void createUserAndAccount()
        {
            // Create a new User (Setup Object)
            User newUser = new User(
                FirstName = 'John',
                LastName = 'Doe',
                Email = 'john.doe@example.com',
                Username = 'john.doe@example.com',
                Alias = 'jdoe',
                TimeZoneSidKey = 'America/Los_Angeles',
                LocaleSidKey = 'en_US',
                EmailEncodingKey = 'UTF-8',
                ProfileId = '00eXXXXXXXXXXXXXX', // Replace with a valid Profile ID
                LanguageLocaleKey = 'en_US'
            );
            insert newUser; // DML operation on a setup object
    
            // Create a new Account (Non-Setup Object)
            Account newAccount = new Account(
                Name = 'Test Account'
            );
            insert newAccount; // DML operation on a non-setup object
        }
    }

    When you execute this code, Salesforce will throw the following error:

    System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)

    This error occurs because the code attempts to perform DML operations on both a setup object (‘User’) and a non-setup object (‘Account’) in the same transaction.

    How to Handle Mixed DML Operations

    To avoid the Mixed DML Operation error, you need to separate the DML operations on setup and non-setup objects into different transactions. Salesforce provides several techniques to achieve this.

    1.Use ‘System.runAs()’ for Setup Objects

    The ‘System.runAs()’ method allows you to execute code in the context of a specific user. You can use this approach to isolate DML operations specifically for setup objects. Modify the previous example:

    Apex

    public class MixedDMLExample {
        public static void createUserAndAccount() {
            // Create a new User (Setup Object)
            User newUser = new User(
                FirstName = 'John',
                LastName = 'Doe',
                Email = 'john.doe@example.com',
                Username = 'john.doe@example.com',
                Alias = 'jdoe',
                TimeZoneSidKey = 'America/Los_Angeles',
                LocaleSidKey = 'en_US',
                EmailEncodingKey = 'UTF-8',
                ProfileId = '00eXXXXXXXXXXXXXX', // Replace with a valid Profile ID
                LanguageLocaleKey = 'en_US'
            );
    
            // Use System.runAs() to isolate the DML operation on the setup object
            System.runAs(new User(Id = UserInfo.getUserId())) {
                insert newUser;
            }
    
            // Create a new Account (Non-Setup Object)
            Account newAccount = new Account(
                Name = 'Test Account'
            );
            insert newAccount; // DML operation on a non-setup object
        }
    }

    By wrapping the DML operation on the ‘User’ object inside ‘System.runAs()’, you ensure that it runs in a separate context, avoiding the Mixed DML Operation error.

    1. Use Future Methods

    Another approach is to use the ‘@future’ annotation to execute DML operations on setup objects asynchronously. This separates the transactions and avoids the Mixed DML Operation error.

    Apex

    public class MixedDMLExample {
        public static void createUserAndAccount() {
            // Create a new Account (Non-Setup Object)
            Account newAccount = new Account(
                Name = 'Test Account'
            );
            insert newAccount; // DML operation on a non-setup object
    
            // Call a future method to handle the setup object DML
            createUserAsync();
        }
    }
    
    @future
    public static void createUserAsync() {
        // Create a new User (Setup Object)
        User newUser = new User(
            FirstName = 'John',
            LastName = 'Doe',
            Email = 'john.doe@example.com',
            Username = 'john.doe@example.com',
            Alias = 'jdoe',
            TimeZoneSidKey = 'America/Los_Angeles',
            LocaleSidKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            ProfileId = '00eXXXXXXXXXXXXXX', // Replace with a valid Profile ID
            LanguageLocaleKey = 'en_US'
        );
        insert newUser; // DML operation on a setup object
    }

    In this example, the developer moves the DML operation on the ‘User’ object to a future method, which runs asynchronously and avoids the Mixed DML Operation error.

    Best Practices to Avoid Mixed DML Errors:

    1. Separate Setup and Non-Setup DML Operations: Always make sure to run DML operations on setup and non-setup objects in different transactions.
    2. Use ‘System.runAs()’ for Setup Objects: This is a simple and effective way to isolate DML operations on setup objects.
    3. Leverage Future Methods: For complex scenarios, use ‘@future’ methods to handle setup object DML operations asynchronously.
    4. Plan Your Transactions: Carefully design your code to avoid mixing DML operations on different types of objects.

    Conclusion

    Mixed DML Operations are a common challenge in Salesforce development, but with a clear understanding of the restrictions and the right techniques, you can easily overcome them. By separating DML operations on setup and non-setup objects using ‘System.runAs()’ or future methods, you can ensure that your code runs smoothly without encountering runtime errors.

    Understanding and applying Salesforce best practices is essential for developing applications that perform optimally and scale efficiently. With this knowledge, you’re now equipped to handle Mixed DML Operations like a pro. Happy coding!

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleExploring the Free Edition of Databricks: A Risk-Free Approach to Enterprise AI
    Next Article Exploring JavaScript ES2025 Edition

    Related Posts

    Development

    spatie/laravel-flare

    August 9, 2025
    Repurposing Protein Folding Models for Generation with Latent Diffusion
    Artificial Intelligence

    Repurposing Protein Folding Models for Generation with Latent Diffusion

    August 9, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-1220 – Apache PHP Null Character Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-37788 – “CXGB4 Memory Leak Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-5779 – “Code-projects Patient Record Management System SQL Injection Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    Urgent WordPress Alert: Motors Theme Flaw (CVE-2025-4322) Actively Exploited for Site Takeover

    Security

    Highlights

    CVE-2025-25251 – FortiClient Mac Incorrect Authorization Privilege Escalation Vulnerability

    May 28, 2025

    CVE ID : CVE-2025-25251

    Published : May 28, 2025, 8:15 a.m. | 1 hour, 10 minutes ago

    Description : An Incorrect Authorization vulnerability [CWE-863] in FortiClient Mac 7.4.0 through 7.4.2, 7.2.0 through 7.2.8, 7.0.0 through 7.0.14 may allow a local attacker to escalate privileges via crafted XPC messages.

    Severity: 7.8 | HIGH

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    This AI Paper Introduce WebThinker: A Deep Research Agent that Empowers Large Reasoning Models (LRMs) for Autonomous Search and Report Generation

    May 7, 2025

    Web Developer Toolbar: Essential Tools for Every Developer in 2025

    April 1, 2025

    CVE-2025-47107 – Adobe InCopy Heap Buffer Overflow Vulnerability

    June 10, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.