Manipulate Records with 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.
Because Apex is a data-focused language and is saved on the Lightning Platform, it has direct access to your data in Salesforce. Unlike other programming languages that require additional setup to connect to data sources, with Apex DML, managing records is made easy! By calling DML statements, you can quickly perform operations on your Salesforce records.
This example adds the TCS account to Salesforce. An account sObject is created first and then passed as an argument to the insert statement, which persists the record in Salesforce.
// Create the account sObject Account acct = new Account(Name='TCS', Phone='(123)456-7890', NumberOfEmployees=100); // Insert the account by using DML insert acct;
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.
ID Field Auto-Assigned to New Records
When inserting records, the system assigns an ID for each record. In addition to persisting the ID value in the database, the ID value is also auto-populated on the sObject variable that you used as an argument in the DML call.
This example shows how to get the ID on the sObject that corresponds to the inserted account.
// Create the account sObject Account acct = new Account(Name='TCS', Phone='(123)456-7890', NumberOfEmployees=100); // Insert the account by using DML insert acct; // Get the new ID on the inserted sObject argument ID acctID = acct.Id; // Display this ID in the debug log System.debug('ID = ' + acctID); // Debug log result (the ID will be different in your case) // DEBUG|ID = 0012w000003exMFAAY
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 ListconList = new List { 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 listToUpdate = new List (); // 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.
Two of the contacts who are in the Finance department should have their titles populated with Financial analyst.
Upserting Records
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.
Upsert Syntax
upsert sObject | sObject[] upsert sObject | sObject[] field
The optional field is a field token. For example, to specify the MyExternalID field, the statement is:
upsert sObjectList Account.Fields.MyExternalId;
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.
This example shows how upsert updates an existing contact record and inserts a new contact in one call. This upsert call updates the existing Josh contact and inserts a new contact, Kathy.
1. Execute this snippet in the Execute Anonymous window of the Developer Console.
// Insert the Josh contact Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance'); insert josh; // Josh's record has been inserted // so the variable josh has now an ID // which will be used to match the records by upsert josh.Description = 'Josh\'s record has been updated by the upsert operation.'; // Create the Kathy contact, but don't persist it in the database Contact kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology'); // List to hold the new contacts to upsert List2. Inspect all contacts in your org.contacts = new List { josh, kathy }; // Call upsert upsert contacts; // Result: Josh is updated and Kathy is created.
Your org will have only one Josh Kaplan record, not two, because the upsert operation found the existing record and updated it instead of creating a new contact record. One Kathy Brown contact record will be there too.
Alternatively, you can specify a field to be used for matching records. This example uses the Email field on Contact because it has idLookup property set. The example inserts the Jane Smith contact, and creates a second Contact sObject, populates it with the same email, then calls upsert to update the contact by using the email field for matching.
NOTE:-If insert was used in this example instead of upsert, a duplicate Jane Smith contact would have been inserted.
1. Execute this snippet in the Execute Anonymous window of the Developer Console.
Contact jane = new Contact(FirstName='Jane', LastName='Smith', Email='jane.smith@example.com', Description='Contact of the day'); insert jane; // 1. Upsert using an idLookup field // Create a second sObject variable. // This variable doesn’t have any ID set. Contact jane2 = new Contact(FirstName='Jane', LastName='Smith', Email='jane.smith@example.com', Description='Prefers to be contacted by email.'); // Upsert the contact by using the idLookup field for matching. upsert jane2 Contact.fields.Email; // Verify that the contact has been updated System.assertEquals('Prefers to be contacted by email.', [SELECT Description FROM Contact WHERE Id=:jane.Id].Description);2. Inspect all contacts in your org.
Your org will have only one Jane Smith contact with the updated description.
Deleting Records
You can delete persisted records using the delete statement. Deleted records aren’t deleted permanently from Lightning Platform, but they’re placed in the Recycle Bin for 15 days from where they can be restored.
This example shows how to delete all contacts whose last name is Smith. If you’ve run the sample for bulk DML, your org should already have two contacts with the last name of Smith. Execute this snippet in the Developer Console using Anonymous Apex, and then verify that there are no contacts with the last name Smith anymore.
Contact[] contactsDel = [SELECT Id FROM Contact WHERE LastName='Smith']; delete contactsDel;Note: This snippet includes a query to retrieve the contacts (a SOQL query). You’ll learn more about SOQL in another unit.
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()); }
Comments
Post a Comment