Salesforce DML Operations | Execution Technique


Salesforce DML Operations | Execution Technique

Salesforce DML Operations 

From this EPISODE, we are gonna discuss very important topics like DML operations, batch apex, triggers, test classes etc.
I would like to request you all to follow the complete series to understand everything about salesforce development.

So Let's get started, In this EPISODE we are gonna discuss how to use salesforce DML operation from very basic to advance.

Let's start with types of DML operation and how it can use.

DML Operation :

The DML operations are :
       1. INSERT
       2. UPDATE 
       3. DELETE
       4. UPSERT

There are two ways to perform DML operations.

1. BY USING DML STATEMENTS

For Example :
=============================================
List<Account> accList = new List<Account>();
 accList.add(new Account(Name='salesfocekid 1'));
 accList.add(new Account(Name='salesforcekid 2'));
 insert accList;
=============================================

2. BY USING DATABASE CLASS

For Example : 
============================================= 
List<Account> accList = new List<Account>();
 accList.add(new Account(Name='salesforcekid 1'));
 accList.add(new Account(Name='salesforcekid 2'));
Database.saveResult[] sr = Database.insert(accList, false);
=============================================

There is one difference between the above two operations. In the Database class method, you can specify whether to allow partial processing of the records if any errors are encountered.
By parsing the boolean value as a parameter to the Database.insert.

If you give the parameter as true, if any error occurs it doesn't allow the operation to continue.
If you specify false the remaining DML operations can still succeed, whereas insert in DML if any one of the records fails the total operation is discarded.
For Example :
=============================================
public pagereference show()
{
  List<Account> acc = new List<Account>();
 Account a1 = new Account(Name='salesforcekid', Industry='Banking');
 Account a2 = new Account(Industry='Banking');
 Account a3 = new Account(Name='salesforcekid', Industry='Banking');
           acc.add(a1);
           acc.add(a2);
           acc.add(a3);

Database.SaveResult[] r = Database.insert(acc,true);
return null;
}
=============================================

In the above program, when we give Database.insert(acc, true), if any error in any of the records a1, a2, a3 the entire operation of the insert is rolled back.

When you give Database.insert(acc, false) for the above statements, if any error occurs in any of the records a1, a2, a3 only that record is terminated and state is saved to save the result class rest of the operation are processed normally.

SOQL DML and Loops :

SOQL for loops iterates overall of the sObject records returned by a SOQL query. The syntax of a SOQL for loop is either.
=============================================
for(variable : [soql_query])
{
  code_block
 }

(or)

for(variable_list : [soql_query])
{
  code_block
}
=============================================

Take a look at following example to understand how you can use this :
Example 1 :
=============================================
String s = 'salesforcekid' ;

for(Account a : [SELECT Id, Name FROM Account WHERE Name = : s])
{
    //Your code Here 
 }
=============================================

Scenario 1 : 
Write a code to fetch list of accounts where account name is 'siebel' and update them by oracle.
=============================================
List<Account> accs = [SELECT Id, Name FROM Account WHERE                                                   Name='siebel'];

//Loop through the list and update the Name field
for(Account a : accs)
{
  a.Name = 'oracle' ;
 }

//Update the database
Update accs ;
=============================================

Scenario 2 :
Write code to fetch list contacts for a given account & update contact email with account email id.
=============================================
Account acc = [SELECT email, (SELECT Id, emailId__c FROM Contacts)                              FROM Account WHERE Name='salesforcekid' LIMIT 1] ;

List<Contact> con = acc.Contacts ;
List<Contact> myContacts = new List<Contact>();
  
 for(contact x : con)
 {
   x.email = acc.emailId__c ;
   myContacts.add(x);
  }
update myContacts;
=============================================

Scenario 3 :
Write a code to fetch all the transaction records which are created yesterday and delete them.
=============================================
List<Transaction__c> tran = [SELECT Id FROM Transaction__c WHERE                                                   createdDate = YESTERDAY];
Delete tran;
=============================================

Scenario 4 :
Write code to create new student records by fetching the data from collage object where the branch is CSE.
=============================================
List<Student__c> std = new List<Student__c>();
List<Collage__c> colg = Database.query ('SELECT Name, Branch__c,                                               Year__c FROM College__c WHERE                                                               branch__c='CSE');

for(collage__c : colg)
{
   student__c s = new student__c();
   s.Name =c.Name;
   s.Branch__c = c.branch__c ;
  std.add(s);
 }
Insert std ;
=============================================

Huh!! Tired ?? It's absolutely fun right !!

So these are the simple scenario-based example to understand when to use what.
Now we will see how we can count the number of DML statements in a transaction.
Example 1 :
=============================================
Account a = new Account(Name='salesforcekid', Industry='Banking');
Insert a; 

Account a1 = new Account(Name='By Ajinkya', Industry='Banking');
Insert a1;
=============================================

In the above example, we used Insert operation 2 times i.e. a and a1.
Example 2 :
=============================================
void show()
{
  Account a = new Account(Name='salesforcekid', Industry='Banking');
  Insert a ;

  Account x = [SELECT Id, Name FROM Account LIMIT 1];
  x.Name = 'sam' ;
  Update x ;

  Account y = [SELECT Id, Name FROM Account LIMIT 1];
  Delete y ;
}
=============================================


In the above example we have performed Insert, Update, Delete hence count is 3.
Now let's perform DML operation in Loop.
For Example :
=============================================
void show()
{
  for(Integer i=1 ; i<=100 ; i++)
 {
   Account a = new Account(Name='sam', Industry='Banking');
   Insert a ;
   }
 }
=============================================
NOTE : In a single transaction we cannot make more than 150 DML statements.

For Example :
=============================================
Void Show()
{
  for(Integer i=1; i<=160; i++)
 {
   Account a = new Account(Name='sam', Industry='Banking');
   Insert a;
 }
}
=============================================

In the above transaction show, we made 160 DML statements, So we get an error like below.
 system.LimitException : Too many DML statements : 151

Now as salesforce don't support DML statements more than 150 there is a way to handle this situation and load large data without any error.

These are the ways to use DML operations in your Apex code.

Now In the upcoming EPISODE, we are gonna discuss how to use these DML operations wisely.  
So Stay tuned for next Episode...



WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE DML OPERATION EPISODE

If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)


<< PREVIOUS                                                      NEXT >>

Salesforce DML Operations | Execution Technique Salesforce DML Operations | Execution Technique Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.