Database DML Methods & SOSL in Salesforce

on

|

views

and

comments

As a Salesforce application developer, we always have a question like how many ways we can perform the DML operations when dealing with transactions. The answer is Salesforce provides 2 ways to perform the DML operations. Let us understand the difference between DML Statements and Database methods in Salesforce.

Table of Contents

Introduction

Let’s start with an example where we wanted to insert the account record.

				
					List<Account> accounts = new List<Account>();
accounts.add(new Account(Name = 'Test Account'));
accounts.add(new Account(Name = 'Test Account'));
System.debug('Account List Size : ' +accounts.size());
insert accounts;
				
			

Using the above approach if any account record insert fails then all the records will fail. so what if We wanted to save the records that were successfully processed and only fail those that failed? then we will use Database class methods for DML

Common Database Methods in Salesforce

  • Insert
  • Update
  • Delete
  • convertLead
  • Query

Approach: All or nothing.

Syntax: Database.insert(List<sObject> object, Boolean);

Syntax: Database.update(List<sObject> object, Boolean);

Syntax: Database.delete(List<sObject> object, Boolean);

Hands-On

				
					// Instance OR Object
List<Account> accountList = new List<Account>();
Account accountRecord = new Account();
accountRecord.Name = 'Amazon.com';
accountRecord.Site = 'https://www.amazon.com';
accountRecord.WebSite = 'https://www.amazon.com';
accountRecord.Rating = 'Cold';
accountList.add(accountRecord); // 0 Index
Account accountRecord1 = new Account();
accountRecord1.Name = 'Flipkart.in';
accountRecord1.Site = 'https://www.Flipkart.in';
accountRecord1.WebSite = 'https://www.Flipkart.in';
accountRecord1.Rating = 'Hot';
accountList.add(accountRecord1);
Integer length = accountList.size(); // 2 , lastIndex length -1
// Partial DML is allwed
List<Database.SaveResult> saveResult = Database.insert(accountList, false);
// saveResult.get(0) // Amazon.com
for(Integer i=0; i<length; i++ ){
    Database.SaveResult sr = saveResult.get(i);
    Account accountRecord = accountList.get(i);
    if(sr.isSuccess()){
        System.debug(sr.getId());
    }else{
        System.debug('Error in Account '+ accountRecord);
        for(Database.Error err : sr.getErrors()) {
            //System.debug('The following error has occurred.');                    
            //System.debug(err.getStatusCode() + ': ' + err.getMessage());
            //System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}
// Iteration #1
// i = 0
// saveResult.get(i) = saveResult.get(0)
// accountList.get(i) = accountList.get(0) // Amazon.com
// i++ = i = i+1
// Iteration #2
// i = 1
// saveResult.get(i) = saveResult.get(1)
// accountList.get(i) = accountList.get(1) // Flipkart.com
/*
Database.insert(accountRecord);
// insance method
// class method
public class Database{
    public static void insert(sObject objectToInsert){
        
    }
}
*/
				
			

Database Class DML Methods vs Normal DML

DML Statements

  1. Partial DML is not allowed. For example, if you have 100 records in the list, then either all the records will be updated or none.
  2. You cannot get the list of successful and failed records.
  3. Example – insert, update

Database Methods

  1. A partial DML is allowed. You can specify the Parameter in the Database method as true or false, true to allow the partial update, and false for not allowing the same
  2. You can get the list of successful and failed records as we have seen in the example.
  3. Example – Database. insert, Database. update

Database Query Method

Database.Query method in Salesforce takes a single string parameter as a Query and returns the List<sObject> as a result.

Dynamic SOQL with Bind in Apex

				
					Map<String, Object> acctBinds = new Map<String, Object>{
        'acctName' => 'Acme Corporation
};

List<Account> accts = 
    Database.queryWithBinds('SELECT Id FROM Account WHERE Name = :acctName',
                            acctBinds, 
                            AccessLevel.USER_MODE);
				
			

Hands-On

				
					public class SOQLDemo {
    
    public void searchAccount(String accountName){
        // Like
        String likeParam = '%'+accountName+'%';
        List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name Like:likeParam];
        System.debug(accountList);
    }
    
    public static void query(String objectApiName, String fieldsToReturn, Integer limitCount,
                             String filterCondition, Map<String, Object> variableBinds){
        // Known information
        // Object API Name
        // Fields to Return
        String queryString = 'SELECT '+fieldsToReturn+' FROM '+objectApiName+' WHERE '+filterCondition+' LIMIT '+limitCount;
        System.debug(queryString);
        // SELECT Id, Name FROM Account WHERE Name Like:likeParam  LIMIT 5
        List<sObject> records = Database.queryWithBinds(queryString, variableBinds, AccessLevel.USER_MODE);
        System.debug('records '+records);
        /*
             Map<String, object> variableBinds = new Map<String, Object>();
            variableBinds.put('likeParam', '%uni%');
            variableBinds.put('accountName', 'Amazon.com');
            SOQLDemo.query('Account', 'Id, Name', 5, 'Name Like:likeParam OR Name =:accountName ',variableBinds);
        */ 
    }
}
				
			

SOSL in Salesforce

SOSL (Salesforce Object Search Language) is used to search a keyword in single or multiple objects. List<List<sObject>>
No DML is Allowed in the result of SOQL.

Hands-On

				
					public class SOSLDemo {

    public static void find(String keyword){
        List<List<sObject>> records = [FIND :keyword IN ALL FIELDS 
                                       RETURNING
                                       Account(Id, Name, Rating, Industry),
                                       Contact(Id, Name, Email),
                                       Opportunity(Id, Name, Amount),
                                       Lead(Id, Name, Email, Company, Phone),
                                       Case(Id, CaseNumber, Subject, Status, Priority),
                                       User(Id, Email, Name, UserName, Title, Department)
                                      ];
        System.debug(records.size());
        List<Account> accountRecords = records.get(0);
        System.debug(accountRecords);
        List<Contact> contactRecords = records.get(1);
        System.debug(contactRecords);
    }
}
				
			

Watch Complete Video

Resources

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential