Friday, August 22, 2014

What is Difference between Database DML statements and simple DML statements?

What is Difference between Database DML statements and simple DML statements?


Let us see 'insert' dml as an example. When we execute the below two statements, how do they differ from each other?

1. Insert accList;
2. Database.insert(accList,false);


**accList is a list of account records.

First let's see simple insert- when we do simple insert on that list it will either insert all of the account records in the list or none will be inserted. That is, there will be either total success or total failure. You cannot have partial success, partial failure in case of simple insert. If any of the record in the list fails due to any validation or any other thing, then none of the records in that list will be inserted. Records will be inserted only if all of the records are good to get inserted(i.e pass all sorts of validations)

Database.insert on the other hand can give you partial success. To get partial success we will have to pass a parameter "opt_allOrNone" as 'false' separated by the list name. If this parameter is set to true then it functions like simple insert. So if the parameter is false, then all the records passing validations will be inserted and others will be restricted.


We can track the errors that are encountered, using saveresult object as shown in the below code snippet,

List<database.saveresult> 
 accResultList = database.insert(accList,false);
for(database.saveresult res:accResultList){
if(!res.issuccess()){
  database.error e = esr.getErrors()[0];
system.debug('error is *******'+e.getmessage());
}



Let us summarise on the points discussed above,

Simple Insert
1. Can insert either all the records or no records at all. Partial success is not possible.

Database.insert(listname,false)
1. Partial success is possible in this case.

Database.insert(listname,true)
1. Operates same like simple insert dml i.e no partial success possible.

Data Loader, if you have observed works on the principle of database methods with "opt_allOrNone" flag set as 'false', hence we get partial success even if any of the record fail.

all of the points discussed above for insert also apply for other DML: update,upsert,delete.









0 comments:

Post a Comment

 
| ,