Salesforce with Ankit

Salesforce beyond the clouds !

About DML in Apex

We will cover DML operations in Apex in this article. Also we will see some examples of them

  1. DML –
    • It is Data Manipulation Language.
  2. Insert –
    • The insert statement saves a new record to the Salesforce database.
    • Note: After insert is performed, the Id field on record is populated by system.
    • For Example:
      • Contact newContact = new Contact (FirstName = ‘Paul’, LastName = ‘Steven’ );
      • insert newContact;
  3. Update
    • The update statement save changes to an existing record to the database, and the record must have the Id field populated.
    • For Example:
      • Contact newContact = new Contact (FirstName = ‘Paul’, LastName = ‘Battisson’);
      • insert newContact;
      • newContact.Email = ‘test@abc.com’;
      • update newContact;
  4. Upsert –
    • The upsert statement requires an external Id field to be populated which the system will use to match on.
    • If match found, an update is performed, else new record is inserted.
    • For Example:
      • Contact newContact = new Contact (FirstName = ‘Paul’, LastName = ‘Battisson’);
      • External_Id_Field__c = ‘MyExternalId’;
      • upsert newContact;
  5. Delete –
    • The delete statement removes a record with the given Salesforce Id from the database.
    • For Example:
      • Contact newContact = new Contact ( FirstName = ‘Paul’, LastName = ‘Battisson’);
      • insert newContact;
      • delete newContact; (Contact is removed from database).
  6. Undelete –
    • Undelete statement restores records from the recycle bin.
    • Example:
      • undelete [select Id, LastName FROM Contact WHERE LastName = ‘Smith’ ALL ROWS];
  7. Merge –
    • Merge statement merges up to 3 records into a single record and removes others.
    • First record is master record, into which other records are merged.
    • For Example:
      • Contact newContact = new Contact (FirstName = ‘Paul’, LastName = ‘Smith’);
      • insert newContact;
      • Contact newContact2 = new Contact (FirstName = ‘Paul’, LastName = ‘Battisson’);
      • insert newContact2;
      • merge newContact newContact2;
  8. Enums –
    • An enum allows you to define preset list of identifiers for abstract types that can be used.
    • Enums are particularly useful when you have a pre-defined list of values that will change.
    • Example:
      • enum Direction {NORTH, SOUTH, EAST, WEST};
      • Direction north = Direction.NORTH;

Thank you for reading the article till the end, in next article we will discuss Collections in Apex.

Published by

Leave a comment