We will cover DML operations in Apex in this article. Also we will see some examples of them
- DML –
- It is Data Manipulation Language.
- 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;
- 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;
- 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;
- 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).
- Undelete –
- Undelete statement restores records from the recycle bin.
- Example:
- undelete [select Id, LastName FROM Contact WHERE LastName = ‘Smith’ ALL ROWS];
- 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;
- 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.
Leave a comment