DML in Apex

Insert statement in DML in Apex

The insert statement in DML in Apex is used to create completely new records in the org.

insert sObject;

Here’s how to use the insert statement:

  • Create a new sObject variable or List.
  • Fill out all the required or additional fields.
  • Call an insert statement to insert the record or list.

After the call, Salesforce will create new records and generate a unique record Id. If you’d like to see some examples, check out our article on sObjects.What if you want to work with existing records instead of creating new ones? Then you need to use an update statement.

Update statement

The update statement is used to save the changes that were made on the records into the database. We usually call this “committing” changes into the database.

still basics of apex advanced 24 1

It’s only possible to update records that already have an Id. Therefore, you need to either query or insert the records to be able to update them later. The syntax is the same as for the insert statement:

update sObject;

Example #1 – Update Contact

Contact contact1 = new Contact();
contact1.Email = 'alex@mail.com';
contact1.LastName = 'Johnson';
insert contact1; // at this point an Id will be generated

System.debug(contact1.LastName);

contact1.LastName = 'Miller';
update contact1;

System.debug(contact1.LastName);

Output

Johnson
Miller
untitled 23

Explanation

If we remove the update line and run the code, we’ll see in the Salesforce UI that the last name hasn’t changed. Without an update statement, all the changes that we make will not be saved. We need an update statement to actually commit the changes into the database (org).

Example #2 – Update Opportunity

// Query opportunity from org with SOQL.
Opportunity opportunity = [
    SELECT StageName
    FROM Opportunity
    WHERE Id = '0067Q00000DTtwTQAT'
    LIMIT 1
];

// Update stage of the opportunity
opportunity.StageName = 'Qualification';

// Update opportunity to commit the changes back into the org.
update opportunity;

Before we run the code, we can check that the stage name is “Prospecting.”

untitled 24

After we run the code, the opportunity will have a different stage name:

untitled 25

Upsert statement

An upsert statement will execute an update on each record that has an Id and insert on each record that doesn’t.

still basics of apex advanced 27 1 1

Example #3 – Upsert

Don’t forget that the Id will be different for your org.

// Create an empty list of contacts
List<Contact> contacts = new List<Contact>();

Contact contact1 = new Contact(); // Create first empty conact
contact1.LastName = 'Johnson'; // Fill out required field
contacts.add(contact1); // Add contact into the list

// Query existing contact
Contact contact2 = [
    SELECT Id, LastName 
    FROM Contact 
    WHERE Id = '0037Q00000TiyFNQAZ' 
    LIMIT 1
];
contact2.LastName = 'Smith'; // Change the last Name to "Smith"
contacts.add(contact2); // Add existing contact into the list

upsert contacts; // upsert the whole list

Here, contact1 will be inserted because it doesn’t have an Id. Meanwhile, contact2 will be updated because it already exists in the system and has an Id.

Lists and DML in Apex

Salesforce has a limit of 150 DML statements. This means you can’t call insertupdate or upsert more than 150 times in your execution. What if you want to insert 200 contacts? Try to run the code below:

for(Integer i = 0; i < 200; i++) {
    Contact myContact = new Contact();
    myContact.LastName = 'Test ' + i;
    insert myContact;
}

You’ll get the following error: System.LimitException: Too many DML statements: 151. That’s because you already called the insert statement 150 times. On the 151st time, Apex recognizes that it’s above the limit and forbids the next insert call.

But you can still insert lists just as you inserted variables before:

List<Contact> contacts = new List<Contact>();

for(Integer i = 0; i < 200; i++) {
    Contact myContact = new Contact();
    myContact.LastName = 'LastName ' + i;
    contacts.add(myContact);
}

insert contacts;

If you run this code, you’ll insert 200 contacts into your system.

Example #4 – Update opportunity stages

The most common use case for update is as follows:

  • Query records from the org with SOQL.
  • Change fields on these records.
  • Update the records to commit the changes back into the org.
// Query opportunities from org with SOQL.
List<Opportunity> opportunities = [
    SELECT Id, Name, StageName
    FROM Opportunity
    WHERE CreatedDate = THIS_MONTH
];

// Update stages on each opportunity
for(Opportunity opportunity : opportunities) {
    opportunity.StageName = 'Closed Won';
}

// Update the records to commit the changes back into the org.
update opportunities;

After you run this code, you can run the query to check if every opportunity that was created this month has the correct status.

still basics of apex advanced 25 1

What we didn’t cover

Database class

There’s an alternative way of doing DML: with the Database class. The most common usage is when you need to make sure that an Exception doesn’t ruin your program. Let’s say you have a list of contacts called myContacts, and you want to insert it.

insert myContacts;

If at least one of the contacts in the List doesn’t have a required field defined, your whole program will fail. In this case, if you use the Database class instead, you can prevent your whole program from failing:

Database.insert(myContacts, false);

The second argument is called allOrNone and is true by default. If you pass false instead and some of your contacts fail, other contacts will still be inserted. This behavior is quite relevant if you have complex validation rules (e.g. they’re defined on the contact and you’re not sure if they’ll pass the validation when you insert the records).

You can read about when to use standard DML and when to use the Database class in the Salesforce documentation. My opinion: just use standard DML as much as possible. The Database class doesn’t signal you when something is wrong with your DML, so you might end up with a few bugs.

Upsert on a field

Upsert has one very useful feature: You can upsert records based on a field.

upsert record field;

In the real world, we use it to upsert records based on an external Id. There are a few other use cases that you can check out in this article, but in the real world, you only use upserts in combination with external Ids.

Read that article and move on. You won’t need this topic until you write an integration with another system.

Delete Statement

The most common usage of Delete is when you’ve inserted some test data into the database and you want to delete it. For example, you inserted 100 contacts called Test.

List<Contact> contacts = new List<Contact>();

for(Integer i = 0; i < 200; i++) {
    Contact myContact = new Contact();
    myContact.LastName = 'Test';
    contacts.add(myContact);
}

insert contacts;

You can run the following script to delete every contact with the name Test:

List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE Name = 'Test'];
delete contacts;

Merge

This statement merges two records of the same type. It can only be called on leads, accounts, cases and contacts. You can read about this statement in the official documentation, but it’s rarely used.

<h4 class="item-title">admin</h4>

admin

Related Posts

blog images 12

SOQL in Apex

blog images 11

Loops in Apex

blog images 10

Lists in Apex

Leave a Reply

Your email address will not be published. Required fields are marked *

t.me/ihor_igor

Subscribe for news about new courses or discounts.

No spam, we promise.


    © 2023 All Rights Reserved by site  igor@cloud-prism.com