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.
- Delete
- Recover(UnDelete)
- Update
- Insert
- Upsert(update and insert in one operation)
- Merge(In case of duplicate Records)
- 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
[…] Next: DML Operation in detail […]
[…] Case for Upsert: Export data from production to sandbox. DML Operations in detail | SalesforceNextGen. DML Operations in detail: Data manipulation language operations mainly consist of insertion of […]