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

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 4, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 4, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 4, 2025

      Smashing Animations Part 4: Optimising SVGs

      June 4, 2025

      I test AI tools for a living. Here are 3 image generators I actually use and how

      June 4, 2025

      The world’s smallest 65W USB-C charger is my latest travel essential

      June 4, 2025

      This Spotlight alternative for Mac is my secret weapon for AI-powered search

      June 4, 2025

      Tech prophet Mary Meeker just dropped a massive report on AI trends – here’s your TL;DR

      June 4, 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

      Beyond AEM: How Adobe Sensei Powers the Full Enterprise Experience

      June 4, 2025
      Recent

      Beyond AEM: How Adobe Sensei Powers the Full Enterprise Experience

      June 4, 2025

      Simplify Negative Relation Queries with Laravel’s whereDoesntHaveRelation Methods

      June 4, 2025

      Cast Model Properties to a Uri Instance in 12.17

      June 4, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      My Favorite Obsidian Plugins and Their Hidden Settings

      June 4, 2025
      Recent

      My Favorite Obsidian Plugins and Their Hidden Settings

      June 4, 2025

      Rilasciata /e/OS 3.0: Nuova Vita per Android Senza Google, Più Privacy e Controllo per l’Utente

      June 4, 2025

      Rilasciata Oracle Linux 9.6: Scopri le Novità e i Miglioramenti nella Sicurezza e nelle Prestazioni

      June 4, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Mastering Database.SaveResult in Batch Class: A Beginner-Friendly Guide

    Mastering Database.SaveResult in Batch Class: A Beginner-Friendly Guide

    January 15, 2025

    Imagine you’re a skilled craftsman working in a massive warehouse. Every day, your task is to process thousands of unique items and ensure that each one is properly logged and stored. But let’s face it — mistakes happen. Sometimes an item gets mislabeled or damaged, and you need to know which ones to fix, and which ones made it safely through. In Salesforce, when working with a batch class that processes thousands or even millions of records, Database.SaveResult acts as your trusty supervisor, keeping track of which records succeeded, and which ones failed.

    Let’s dive into the world of Database.SaveResult in batch classes with an easy-to-follow narrative that will make this topic clear and interesting, even for beginners.

    Setting the Scene: What Is Database.SaveResult?

    Before jumping into batch classes, let’s first understand what Database.SaveResult is. Whenever you perform DML (Data Manipulation Language) operations like insert, update, or delete, Salesforce gives you feedback. This feedback tells you whether the operation was successful or if something went wrong. In the case of partial successes (when some records succeed while others fail), this feedback comes in the form of a Database.SaveResult object.

    Think of it as a results sheet from an exam. For every record, it tells you:

    • Whether it passed or failed.
    • If it failed, what the error was.

    Now, let’s see how this applies to batch classes.

    Batch Class Basics

    A batch class is like a super-efficient worker in Salesforce. When you have a huge number of records to process (thousands or even millions), a batch class breaks the job into smaller, manageable chunks called batches. Each batch is processed separately, ensuring the system doesn’t get overwhelmed.

    Here’s a simple example to paint the picture:

    Let’s say your company sells products, and you want to update the stock levels of 100,000 items in your inventory. Instead of trying to update them all at once (and risking errors or timeouts), you use a batch class to process them in batches of, say, 200 records at a time.

    The Role of Database.SaveResult in Batch Classes

    In a batch class, you often perform DML operations inside the execute method. But what happens if some records fail to save? That’s where Database.SaveResult comes in. It acts like a detailed logbook, showing you exactly which records succeeded and why any failures occurred.

    Mastering Database.saveresult In Batch Class A Beginner Friendly Guide Visual Selection

    Here’s how it works step by step:

    1. Perform a DML Operation Use methods like Database.insert(), Database.update(), or Database.delete(). These methods allow you to process records in bulk and capture the result using Database.SaveResult.
    2. Capture the Results The result of the DML operation is stored in a list of Database.SaveResult objects.
    3. Handle Successes and Failures Loop through the results to identify which records were successful and handle errors for the failed ones.

    Example: A Simple Batch Class

    Here’s an example to demonstrate how to use Database.SaveResult in a batch class:

    public class UpdateAccountBatch implements Database.Batchable<SObject>, Database.Stateful {
        private List<Id> errorIds = new List<Id>();
    
        public Database.QueryLocator start(Database.BatchableContext bc) {
            // Query for accounts to update
            return Database.getQueryLocator('SELECT Id, AnnualRevenue FROM Account');
        }
    
        public void execute(Database.BatchableContext bc, List<Account> scope) {
            try {
                // Update accounts with new annual revenue
                for (Account acc : scope) {
                    acc.AnnualRevenue = acc.AnnualRevenue != null ? acc.AnnualRevenue * 1.1 : 100000;
                }
    
                // Perform DML and capture results
                Database.SaveResult[] results = Database.update(scope, false);
    
                // Process results
                for (Integer i = 0; i < results.size(); i++) {
                    if (!results[i].isSuccess()) {
                        errorIds.add(scope[i].Id); // Store failed record Ids
                        for (Database.Error err : results[i].getErrors()) {
                            System.debug('Failed to update Account Id: ' + scope[i].Id + ' Error: ' + err.getMessage());
                        }
                    } else {
                        System.debug('Successfully updated Account Id: ' + scope[i].Id);
                    }
                }
            } catch (Exception e) {
                System.debug('Unexpected error occurred: ' + e.getMessage());
            }
        }
    
        public void finish(Database.BatchableContext bc) {
            if (!errorIds.isEmpty()) {
                String subject = 'Batch Job Completed with Errors';
                String body = 'The batch job encountered errors while processing the following Account IDs:n' + String.join(errorIds, ', ');
    
                // Send email notification
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(new String[] { 'admin@example.com' });
                email.setSubject(subject);
                email.setPlainTextBody(body);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
            }
    
            System.debug('Batch job finished. Error IDs: ' + errorIds);
        }
    }

     

    Mastering Database.saveresult In Batch Class A Beginner Friendly Guide Visual Selection (1)

    1. Partial Success Handling:

      • The Database.update(scope, false) method allows partial success, meaning the system will try to save as many records as possible even if some fail.
      • The results are stored in a list of Database.SaveResult objects.
    2. Error Logging:

      • For every failed record, the error is retrieved using the getErrors() method of SaveResult. This helps identify and fix issues without reprocessing all records.
    3. Scalability:

      • Dividing the job into smaller batches allows the batch class to process efficiently while staying within governor limits.

    Why Use Database.SaveResult?

    You might wonder, why not just use standard DML operations like insert or update without worrying about SaveResult? The answer lies in reliability and flexibility:

    Mastering Database.saveresult In Batch Class A Beginner Friendly Guide Visual Selection (2)

    • Error Tracking: With Database.SaveResult, you can track exactly which records failed and why.
    • Partial Success: Standard DML operations fail entirely if one record has an issue. Using methods like Database.update() with SaveResult, you can save valid records while logging errors for invalid ones.
    • User Experience: Imagine running a batch job on 10,000 records. If even one record fails and you’re using standard DML, the entire operation rolls back. With SaveResult, you avoid this problem.

    Common Questions and Answers

    1. What happens if I don’t handle SaveResult errors?
    Errors will still occur, but you won’t have visibility into what failed or why. This can make debugging very difficult.

    2. Can I retry failed records automatically?
    Yes, you can capture the failed records and rerun them in another batch job or after fixing the issues.

    3. Is Database.SaveResult limited to batch classes?
    No, it can be used in any Apex context where DML operations are performed.

    Wrapping Up

    Database.SaveResult is a powerful tool for handling bulk DML operations in Salesforce, especially in batch classes. By understanding how to use it effectively, you can ensure reliable, scalable, and user-friendly data processing.

    Think of it as your record-by-record performance review sheet. With it, you’ll never be in the dark about what went wrong — or right — in your batch jobs. Start experimenting today and unlock the true potential of your Salesforce data processing!

    Source: Read More 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleKey Insights from the Front-End Meetup by the Front-End Meetup Group
    Next Article Unlock the Future of Integration with IBM ACE

    Related Posts

    Security

    HPE StoreOnce Faces Critical CVE-2025-37093 Vulnerability — Urges Immediate Patch Upgrade

    June 4, 2025
    Security

    CISA Adds Qualcomm Vulnerabilities to KEV Catalog

    June 4, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    CVE-2025-3300 – “WordPress WPMasterToolKit Directory Traversal Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    New Xbox games launching this week, from May 5 through May 11 — Revenge of the Savage Planet hits Xbox Game Pass

    News & Updates

    5 Major Concerns With Employees Using The Browser

    Development

    ES6: Set Vs Array- What and When?

    Development

    Highlights

    CVE-2025-4077 – Code-projects School Billing System Stack-Based Buffer Overflow Vulnerability

    April 29, 2025

    CVE ID : CVE-2025-4077

    Published : April 29, 2025, 6:15 p.m. | 52 minutes ago

    Description : A vulnerability classified as critical was found in code-projects School Billing System 1.0. This vulnerability affects the function searchrec. The manipulation of the argument Name leads to stack-based buffer overflow. It is possible to launch the attack on the local host. The exploit has been disclosed to the public and may be used.

    Severity: 5.3 | MEDIUM

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

    CVE-2025-27706 – Absolute Secure Access Cross-Site Scripting

    May 28, 2025

    How to Install DeepSeek on Ubuntu 24.04 (Locally)

    February 11, 2025

    Okta Warns of Credential Stuffing Attacks Targeting Customer Identity Cloud

    May 30, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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