Wednesday , August 23 2017
Home / Apex / Apex Programming for beginners / DML Operations in detail

DML Operations in detail

DML Operations in detail:

Data manipulation language operations mainly consist of insertion of record and committing it to the database, but we can also do following operations.

  1. Delete
  2. Recover(UnDelete)
  3. Update
  4. Insert
  5. Upsert(update and insert in one operation)
  6. Merge(In case of duplicate Records)
  7. Converting Leads

 

Inserting and updating the records

Records can be inserted and updated in the database. Records can be created individually or in bulk using the apex collection.

 

For ex: To insert an account just type the below line of code

 

Insert Acc; (Where Acc is an account sObject)

 

Similarly to insert if we want to update a record we write below line of code

 

Update Acc;

 

Inserting Related record, where the relationship is already been established between the objects, they are associated together through a foreign key for example while creating a contact record we can specify its account by providing the account Id which is the foreign key in this scenario.

 

Ex:

Account parentContactAcnt = new Account(Name=”Account for Contact”);

Insert parentContactAcnt;   //// using the id generated from this account and provide as a foreign key.

 

ID idforForeignKey = parentContactAcnt.Id;

 

Contact newCon = new Contact(

Firstname = “Test”;

LastName = “Contact”;

Phone = “111.222.333”;

AccountId = idforForeignKey;

);

Insert newCon;

 

Updating related records, is a bit more tricky then inserting related records and therefore we have to make two separate update call to update the related records. For example if we are updating a contact and we also want to update its account information, then to update account we have to make a separate DML call, see below for more detail :-

 

Ex:

Account parentContactAcnt = new Account(Name=”Account for Contact”);

Insert parentContactAcnt;   //// using the id generated from this account and provide as a foreign key.

 

ID idforForeignKey = parentContactAcnt.Id;

 

Contact newCon = new Contact(

Firstname = “Test”;

LastName = “Contact”;

Phone = “111.222.333”;

AccountId = idforForeignKey;

);

Insert newCon;

 

newCon.Phone = “223.334.445”;

newCon.account. Industry = ‘Technology’;

 

update newCon;

update newCon.account;     //// Separate DMl call to update parent record

 

 

Records can be related to each other using external Id as well, but this relationship has to be defined beforehand to relate any records.

 

Next: Other DML Operations

About Sumit Datta

Check Also

DML Operation

DML Operation contd Upserting records This command incorporates two DML operation i.e. insert and update …

Leave a Reply

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