Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    • How to Use Graph API for Outlook-Salesforce Connection
    • Enhancing Performance with File Compression in Apex
    • Salesforce Spring ’25 Release: Top Flow Enhancements You Need to Know
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Thursday, May 8
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Optimizing Salesforce Apex Code

    Optimizing Salesforce Apex Code

    Dhanik Lal SahniBy Dhanik Lal SahniDecember 8, 2021Updated:January 15, 20257 Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Optimizing Salesforce Apex Code
    Share
    Facebook Twitter LinkedIn Pinterest Email

    To handle business requirements, we have to do a lot of customization in the Salesforce Application. Mostly, we customize apex code for record DML operations, such as when the record is created or updated, performing some business logic, or when deleting a record, performing some validation logic. This customization adds complexity to our application, and if it is not coded well, it will impact our application’s performance. This post will help in Optimizing Salesforce Apex Code, which is added for handling business requirements.

    Below are all possible code optimizations that can be made while querying it or performing DML operations in apex code.

    1. DML or SOQL Inside Loops
    2. Limiting data rows for lists
    3. Disabling Debug Mode for production
    4. Stop Describing every time and use Caching of the described object
    5. Avoid .size() and use .isEmpty()
    6. Use Filter in SOQL
    7. Limit depth relationship code
    8. Avoid Heap Size
    9. Optimize Trigger
    10. Bulkify Code
    11. Foreign Key Relationship in SOQL
    12. Defer Sharing Rules
    13. Use collections like Map
    14. Querying Large Data Sets
    15. Use Asynchronous methods
    16. Avoid Hardcode in code
    17. Use Platform Caching
    18. Use property initializer for test class
    19. Unwanted Code Execution

    In the code practice series, we will discuss each of the above approaches. In this post, let’s examine the first good code practice (DML or SOQL Inside Loop).

    DML or SOQL Inside Loops:

    SOQL is a query language that retrieves data from salesforce objects and DML is a data manipulation language that inserts/updates or deletes records in Salesforce Object.

    What problem can occur If we use DML or SOQL in loops?

    Salesforce has a government limit of 100 SOQL and 150 DML in one transaction. If we write code that will execute a query over 100 or DML over 150, we will get Error: System.LimitException: Too many SOQL queries: 101 or  System.LimitException: Too many DML statements. So we should code so that it does not reach that threshold.

    So let us see examples of where we can face limit exceptions and what ways we can avoid DML/SOQL inside the loop.

    Use Case:

    Take an example. We have an Account object that holds insurance customer information. When a record is updated, we will update the related address object. This is a very simple requirement, and we can write the code below for it. Yes, we can do this using flow, but for understanding, we will write code.

    DML Inside Loop and SOQL Inside Loop

    If we see the above code, it will perfectly work when you take action from a UI like the lightning page, as it will take action for a single record only. But assume later on that the account object will be updated from any data import tool or it will be updated in a batch job that will update thousands of records at once. In that case, will the above code work?

    No, it will not work and throw the above-mentioned System.LimitException error. Why? If you look at the above code carefully, you will see that we are using SOQL in a loop, and we can only query 100 SOQL in one transaction, so the above code will not work. So, how do we handle this SOQL limit exception?

    DML inside loop

    We can resolve the SQOL limit exception by getting all account IDs in the loop and using those account IDs in SOQL once (like lines # 3-10). Now, the above code will not throw exceptions as we have handled SOQL inside for loop issues. But when this trigger executes from the data update tool, it will still throw Too many DML statements exception when records are more than 150 to update. Let us handle that exception also

    DML and SOQL inside loop resolved | Optimizing Salesforce Apex Code

    Instead of updating records in a loop, we can update fields in a collection and update an object at once (code lines # 11-15). Now, our code is good in respect to DML or SOQL inside a loop. Our SOQL is not in the loop, and DML is also not in the loop. There is still one issue in the code related to unwanted code execution, which we will see in later posts.

    Summary:

    Apex code executed in an atomic transaction. When we code, we should avoid more than 100 SOQL or 150 DML statements in a single transaction. While coding, we should never think about single record processing; always code that will work in bulk record processing. We should also consider that a particular code block can be executed from other record insertions or updations. Like account trigger can be fired from contact record updation also, so no of SQOL can increase if we have multiple dependent objects. We will see these fixes in later posts.

    This optimization technique is also applicable to flow execution. If we have created a record trigger flow, then that flow will execute for each record when the bulk record is processed. So, a similar approach is required in flow.

    Similar Posts:

    •  Avoid Batch Apex and Use Queueable Class
    • How to Correctly Publish Platform Event Using Salesforce Apex
    • How to Manage Technical Debt in Salesforce
    • Best Practices to Avoid Hardcoding in Apex for Cleaner Salesforce Code
    • Best Code Analysis Tools For Salesforce Development
    • Implementing Apex Cursors for Optimal Resource Management in Salesforce
    • Salesforce DevOps for Developers: Enhancing Code Quality and Deployment Efficiency
    • Dynamic Code Execution using Callable Interface
    • Apex Code Coverage In Custom Object

    References:

    Error: System.LimitException: Too many SOQL queries: 101

    apex apex code best practice apex code optimization Asynchronous apex best practices in salesforce code optimization code optimization in salesforce DML salesforce salesforce coding best practices Scheduled Apex
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDynamic Record Page Creation using FieldSet
    Next Article Optimizing Loop in Apex Code
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    Unlock the Power of Vibe Coding in Salesforce

    April 30, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Dynamic Queueable Chaining in Salesforce Apex

    April 21, 2025
    By Dhanik Lal Sahni5 Mins Read

    How to Implement Basic Queueable Chaining in Salesforce Apex

    March 31, 2025
    View 7 Comments

    7 Comments

    1. Pingback: Optimize Code by Disabling Debug Mode | SalesforceCodex

    2. Pingback: Optimize Apex Code by Metadata Caching | SalesforceCodex

    3. Pingback: Optimize SOQL Filter in Apex Code | SalesforceCodex

    4. Pingback: Queueable Vs Batch Apex In Salesforce

    5. Pingback: Boost Performance of Salesforce Service Cloud - Vagmine Cloud Solution

    6. Pingback: Questions for Tech Lead/Salesforce Architect Interview

    7. Pingback: Integrate Google reCaptcha v3 into the Salesforce Sites

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    • How to Choose Between SOQL and SOSL Queries July 31, 2024
    Archives
    Categories
    Tags
    apex (110) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) file upload (3) flow (14) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (64) lightning-combobox (5) lightning-datatable (10) lightning component (29) Lightning web component (61) lwc (50) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (139) salesforce apex (46) salesforce api (4) salesforce api integration (5) Salesforce GraphQL API (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) shopify api (3) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

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

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.