What is DML in Apex ?
Data Manipulation Language (DML)
Create and modify records in Salesforce by using the Data Manipulation Language, abbreviated as DML. DML provides a straightforward way to manage records by providing simple statements to insert, update, merge, delete, and restore records.
# DML Statements:
The following DML statements are available.
- insert
- update
- upsert
- delete
- undelete
- merge
Each DML statement accepts either a single sObject or a list (or array) of sObjects. Operating on a list of sObjects is a more efficient way for processing records.
All those statements, except a couple, are familiar database operations. The upsert and merge statements are particular to Salesforce and can be quite handy.
The upsert DML operation creates new records and updates sObject records within a single statement, using a specified field to determine the presence of existing objects, or the ID field if no field is specified.
The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records.
# Apex DML Statements :
Insert Statement :
The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to your organization’s data. insert is analogous to the INSERT statement in SQL.
Account newAcct = new Account(name = 'Acme');
try {
insert newAcct;
} catch (DmlException e) {
// Process exception here
}
Update Statement :
The update DML operation modifies one or more existing sObject records, such as individual accounts or contacts, in your organization’s data. update is analogous to the UPDATE statement in SQL.
Account a = new Account(Name='Acme2');
insert(a);
Account myAcct = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :a.Id];
myAcct.BillingCity = 'San Francisco';
try {
update myAcct;
} catch (DmlException e) {
// Process exception here
}
Upsert Statement :
If you have a list containing a mix of new and existing records, you can process insertions and updates to all records in the list by using the upsert statement. Upsert helps avoid the creation of duplicate records and can save you time as you don’t have to determine which records exist first.
The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively, you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you can specify any field that has the idLookup property set to true. For example, the Email field of Contact or User has the idLookup property set.
List<Account> acctList = new List<Account>();
// Fill the accounts list with some accounts
try {
upsert acctList;
} catch (DmlException e) {
}
Upsert uses the sObject record's primary key (the ID), an idLookup field, or an external ID field to determine whether it should create a new record or update an existing one:
- If the key is not matched, a new object record is created.
- If the key is matched once, the existing object record is updated.
- If the key is matched multiple times, an error is generated and the object record is neither inserted or updated.
Delete Statement :
The delete DML operation deletes one or more existing sObject records, such as individual accounts or contacts, from your organization’s data. delete is analogous to the delete() statement in the SOAP API.
Account[] doomedAccts = [SELECT Id, Name FROM Account WHERE Name = 'DotCom'];
try {
delete doomedAccts;
} catch (DmlException e) {
// Process exception here
}
Undelete Statement :
The undelete DML operation restores one or more existing sObject records, such as individual accounts or contacts, from your organization’s Recycle Bin. undelete is analogous to the UNDELETE statement in SQL.
Account[] savedAccts = [SELECT Id, Name FROM Account WHERE Name = 'Universal Containers' ALL ROWS];
try {
undelete savedAccts;
} catch (DmlException e) {
// Process exception here
}
Merge Statement :
The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records.
List<Account> ls = new List<Account>{new Account(name='Acme Inc.'),new Account(name='Acme')};
insert ls;
Account masterAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme Inc.' LIMIT 1];
Account mergeAcct = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
try {
merge masterAcct mergeAcct;
} catch (DmlException e) {
// Process exception here
}
# Bulk DML :
You can perform DML operations either on a single sObject, or in bulk on a list of sObjects. Performing bulk DML operations is the recommended way because it helps avoid hitting governor limits, such as the DML limit of 150 statements per Apex transaction. This limit is in place to ensure fair access to shared resources in the Lightning Platform. Performing a DML operation on a list of sObjects counts as one DML statement, not as one statement for each sObject.This example inserts contacts in bulk by inserting a list of contacts in one call. The sample then updates those contacts in bulk too.
1. Execute this snippet in the Developer Console using Anonymous Apex.
// Create a list of contacts
List<Contact> conList = new List<Contact> {
new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
new Contact(FirstName='Kim',LastName='Shain',Department='Education')};
// Bulk insert all contacts with one DML call
insert conList;
// List to hold the new contacts to update
List<Contact> listToUpdate = new List<Contact>();
// Iterate through the list and add a title only
// if the department is Finance
for(Contact con : conList) {
if (con.Department == 'Finance') {
con.Title = 'Financial analyst';
// Add updated contact sObject to the list.
listToUpdate.add(con);
}
}
// Bulk update all contacts with one DML call
update listToUpdate;
2. Inspect the contacts recently created in your org.
# DML Statement Exceptions :
If a DML operation fails, it returns an exception of type DmlException. You can catch exceptions in your code to handle error conditions.This example produces a DmlException because it attempts to insert an account without the required Name field. The exception is caught in the catch block.
try {
// This causes an exception because
// the required Name field is not provided.
Account acct = new Account();
// Insert the account
insert acct;
} catch (DmlException e) {
System.debug('A DML exception has occurred: ' +
e.getMessage());
}
# Database Methods:
Apex contains the built-in Database class, which provides methods that perform DML operations and mirror the DML statement counterparts.These Database methods are static and are called on the class name.
- Database.insert()
- Database.update()
- Database.upsert()
- Database.delete()
- Database.undelete()
- Database.merge()
Unlike DML statements, Database methods have an optional allOrNone parameter that allows you to specify whether the operation should partially succeed. When this parameter is set to false, if errors occur on a partial set of records, the successful records will be committed and errors will be returned for the failed records. Also, no exceptions are thrown with the partial success option.
The Database methods return result objects containing success or failure information for each record. For example, insert and update operations each return an array of Database.SaveResult objects.
Database.SaveResult[] results = Database.insert(recordList, false);
Differences between Database Methods and DML Statements :
DML Statements | Database Methods |
---|---|
You cannot get the list of success and failed records. | You can get the list of success and failed records as we have seen in the example. |
Partial Update is not allowed. For example, if you have 100 records in list, then either all the records will be updated or none. | Partial update is allowed. You can specify the Parameter in Database method as true or false, true to allow the partial update and false for not allowing the same. |
Example − insert accounts; | Example − Database.insert(listName, False), where false indicate that partial update is not allowed. |
Resources:
# Manipulate Records with DML - Trailhead Module.
Comments
Post a Comment