1.3 Use DML to manipulate data

The concept

SObjects are records in Salesforce platform. So they can definitely be persisted in Salesforce’s cloud database. The approach, is by using DML statements or Database class methods. Like SObject, DML statement is first class citizen in Apex. They will be treated as normal statements, instead of just strings in most other programming languages.

Let’s take a look at the code.

Merchandise__c mer = new Merchandise__c();
mer.name = 'Bag';
mer.Original_Price__c = 100;
mer.Discount_Type__c = 'Half price';
mer.Discounted_Price__c = mer.Original_Price__c * 0.5;

insert mer;

mer.Discounted_Price__c -= 10; //further discount
update mer;

Merchandise__c mer2 = new Merchandise__c();
mer2.name = 'clothes';
mer2.Original_Price__c = 150;
mer2.Discount_Type__c = 'Normal price';
mer2.Discounted_Price__c = mer.Original_Price__c;

mer.Discounted_Price__c += 10; //further discount is over now;
List<Merchandise__c> merList = new List<Merchandise__c>();
merList.add(mer);
merList.add(mer2);
upsert merList;

You should be able to see two new records created in Salesforce after executing this piece of code.

A bit explanation

If you are familiar with Database, you will probably find insert and update very familiar to you. If not, it is still easy to guess by their meaning. Insert means add new record into database while update means update an existing one. Please be aware that all the DML operators can apply to either one record, or a list of records. And preferably, if you can, always try to do it on a list of record. We will explain the reason later in bulkification post.

Upsert is something new in Apex. It simply means, if the record is new, insert it, or otherwise, update.

Besides insert, update and upsert, you can also do delete. Delete simply means delete a record. It is also easy to use.

Exercise

Create a record and then delete it. See how delete works.

Next Post

1.4 DML executes in one transaction

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Comments

  1. Ankit Panjwani - December 24, 2016 @ 1:55 am

    Hello,

    Where do we write this piece of code in Salesforce org?

    Thanks
    Ankit

    • LanceShi - December 24, 2016 @ 11:04 am

      Please refer to this first post for where to write the code.

Leave a Reply

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