Data Manipulation Language
Data Manipulation Language
Data Manipulation Language is the way we perform CRUD operations in the database i.e. create, retrieve, update and delete records in the Salesforce Database.
DML operations are carried on within a transaction, which is either successfully completed or if an error is encountered then the whole transaction is rolled back.
All operations which can either start in a trigger, apex class method, or anonymous code block. When they run in a transaction they are considered as a single unit of operations. They also include chaining of procedure which is called from inside a transaction operation, for ex a class method updates a record which in turn begins execution of the trigger. They are all part of a single transaction.
DML consists of following statements.
- Insert
- Update
- Upsert
- Delete
- Merge
- Undelete
- Converting Leads
DML can be performed on a single record or to a batch or collection of records. Salesforce allows only 150 DML iteration per transaction, therefore it is advised that we should perform DML on a collection rather on a single record, it improves the overall execution efficiency of the code.
Ex: inefficient code=>
For(account a: accountlist){
If(a.name ==”somevalue”){
a.phone = “9999999999”;
}
Update a;
}
Ex: More Efficient code=>
List<Account> acctoUpdate = new list<Account>();
For(account a: accountlist){
If(a.name ==”somevalue”){
a.phone = “9999999999”;
}
acctoUpdate .add(a);
}
Update acctoUpdate;
DML and Database Class methods
Apex has offered Data manipulation in two ways, DML operations or the use of Database class method.
Ex: DML
List<Account> accountList = new List<Account>();
accountList.add( new Account(Name=”Test1”));
accountList.add( new Account(Name=”Test2”));
insert accountList;
Database Class
List<Account> accountList = new List<Account>();
accountList.add( new Account(Name=”Test1”));
accountList.add( new Account(Name=”Test2”));
Database.SaveResult[] SaveResultList = Database.insert(accountList, false);
If the parameter passed in the method is true, then it behaves exactly same as the DML insert operation.
The main reason to use Database Class over the DML operation is the ability to partially process records if an error is encountered, in DML the whole transaction is roll backed in case of an exception.
You can use DML if you want to through Apex Exception immediately interrupting the control flow.
Next: DML Operation in detail
[…] Next: Data Manipulation Language DML […]
[…] = new Account(Name=”Account for Contact”); ID idforForeignKey = parentContactAcnt.Id; Data Manipulation Language | SalesforceNextGen. Data Manipulation Language Data Manipulation Language is the way we perform CRUD operations in the […]