In Salesforce, DML (an abbreviated version of Data Manipulation Language) enables developers to manipulate data through the use of DML statements. Although it’s great knowing Apex & Triggers, we still need a way to modify our data once we meet certain logic criteria. This is why it’s a crucial tool to use in day-to-day Apex development as without this (or Database Methods), you won’t be able to change your data.
Side note: All operations that can be performed with DML, can be achieved with database methods; although there are a few advantages to Database Methods. We’ll look into Database Methods in the next post!
There are 6 different DML statements in total that can be utilised to modify data in Salesforce.
-
Insert
-
This allows you to insert a new record into the database
-
-
Update
-
This allows you to update an already existing record inside the database
-
-
Upsert
-
This allows you to either update an existing record, or if no record matches the provided record ID, insert a new record.
-
-
Delete
-
This allows you to delete an existing record in the database
-
-
Undelete
-
This allows you to remove a record from the recycle bin and back into the database
-
-
Merge
-
This allows you to combine 2 existing records together to make just 1 record
-
3 Examples Of DML Statements In Apex
Insert Statement
Account insertAccount = new Account(name = 'Google');
try {
insert insertAccount ;
} catch (DmlException e) {
// Error handling
}
Update Statement
Account insertAccount = new Account(Name='Costco');
insert(insertAccount );
Account updateAccount = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :insertAccount.Id];
updateAccount.BillingCity = 'San Francisco';
try {
update updateAccount ;
} catch (DmlException e) {
// Error Handling
}
Merge Statement
List<Account> accountList = new List<Account> {new Account(name='Facebook'),new Account(name='Meta')};
insert accountList ;
Account primaryAccount = [SELECT Id, Name FROM Account WHERE Name = 'Meta.' LIMIT 1];
Account mergeAccount= [SELECT Id, Name FROM Account WHERE Name = 'Facebook' LIMIT 1];
try {
merge primaryAccount mergeAcct;
} catch (DmlException e) {
// Error handling
}