SaasGuru Logo

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉

Kickstart your career with the World's First Salesforce & AI Programs by an IIT - Explore Courses 🎉
DML Statements in Salesforce Apex

DML Statements in Salesforce Apex

Data manipulation is a cornerstone of any application, and Salesforce Apex is no different.  Whether you’re building a simple integration or a complex automation, understanding Data Manipulation Language (DML) concepts in Apex is essential. This blog will guide you through core DML operations and the nuances of working with them in Salesforce.

DML is an abbreviation of Data Manipulation Language. It is used to create, modify, delete, merge data into a database. DML is a critical component of Apex because practically every business case involves database changes and alterations.

DML Statements does not permit partial execution. 

Example, if you have 100 accounts to Insert, if one of the 100 record fails, this will roll back the complete transaction.

Database Methods allows partial execution and also returns success or failure result objects.

saasguru salesforce labs
Example, Database.SaveResults response = Database.insert(IstAccountsTolnsert, false);

Apex DML Statements

A single sObject or a List<sObject> is accepted by each DML expression. Partial update is not possible using the DML statements. Following are the available DML statements:

  • Insert
  • Update
  • Upsert
  • Delete
  • Undelete
  • Merge

Insert Statement

Insert operation can be used in Salesforce to create a new or a list of records in a standard or custom Object. 

Syntax

  • insert sObject
  • insert sObject []

Example 

//Example 1: Insert sobject

//Inserting new sObject – Account with name as ‘ABC Pty Ltd’

Account accountSObject = new Account (Name= ‘ABC Pty Ltd’ );

insert accountsobject;

/*

 

* Example 2: Insert sObject[]

* Inserting new list of sobject –

* Accounts with name as ‘ABC Pty Ltd’ and ‘XYZ Pty Ltd’

* /

List<Account> lstAccounts = new List<Account> () ;

1stAccounts.add(new Account (Name=’ABC Pty Ltd’ ));

1stAccounts.add(new Account (Name=’XYZ Pty Ltd’ ));

insert lstAccounts;)

Update Statement

In Salesforce, update operations can be used to modify an existing record or a list of records in a standard or custom object.

Syntax

  • update sObject
  • update sObject []

Example 

//Example 1: Update sobject

//SOQL can be used to fetch the existing record from the database.

Account existingAccount = [SELECT Id FROM Account WHERE Name = ‘ABC Pty Ltd’ LIMIT 1];

existingAccount. Type = ‘Prospect’;

update existingAccount;

\/*|

 

* Example 2: Update sobject(]|

* Inserting new list of sObject – Accounts with name as ‘ABC Pty Ltd’ and ‘XYZ Pty Ltd’

* Updated the created list with Type as Prospect.

* /

List<Account> IstAccounts = new List<Account> () ;

1stAccounts.add(new Account (Name=’ABC Pty Ltd’ ));

1stAccounts.add(new Account (Name»’XYZ Pty Ltd’ ));

insert 1stAccounts;

//update syntax

List<Account> lstAccountToUpdate = new List<Account>() ;

for (Account eachAccount : lstAccounts) {

eachAccount. Type = ‘Prospect’;

1stAccountToUpdate. add (eachAccount) ;

}

update lstAccountToUpdate;

Upsert Statement

Within a single statement, the upsert statement can be used to create new records or update existing records. We can specify either an external ID field or a record’s Id as a key; by default, an Id is utilized. If the key matches the existing records, the existing record is updated; otherwise, a new record is created. When a key is matched several times, the Upsert statement throws an error. The running user should have View All Data or View All object-level permission if the external id given in the upsert command is not unique.

Syntax

  • upsert sObject | | upsert sObject field
  • upsert sObiect [] | | upsert <sObject [] field

Example 

//Example 1: Upsert sobject

//Inserting new sObject – Account with name as ‘ABC Pty Ltd’

Account accountSObject = new Account (Name=’ABC Pty Ltd’ );

insert accountsobject;

System.debug(‘accountSObject = ‘+accountSObject);

// |DEBUG |accountSObject = Account: (Name=ABC Pty Ltd, Id=0010I00002Ywkg7QAB}

Account accountSObjectWithoutId = new Account (Name=’ PQR Pty Ltd’ ) ;

accountSObject. Type = ‘Prospect’ ;

//Upserting both the sobject

List<Account> IstAccountToUpsert = new List<Account>(accountSObject, accountSObjectWithoutId);

upsert 1stAccountToUpsert;

System.debug (‘1stAccountToUpsert = ‘+1stAccountToUpsert) ;

DEBUG | 1stAccountToUpsert = (Account: {Name=ABC Pty Ltd, Id=0010100002Ywkg7QAB, Type=Prospect} ,

Account: {Name=PQR Pty Ltd, Id=0010100002Ywkg8QAB})

*/

Delete Statement

This command is used to delete a single or a list of records in a standard or custom object.

Syntax

  • delete sObject
  • delete sObject []

Example 

//Example 1: Delete sObject

Account existingAccount = [SELECT Id FROM Account WHERE Name = ‘ABC Pty Ltd’ LIMIT 1];

delete existingAccount;

 

//Example 2: Delete sObject [ ]l

List<Account> 1stAccountToInsert = new List<Account> () ;

1stAccountToInsert.add (new Account (Name=’ ABC Pty Ltd’ ));

1stAccountToInsert.add (new Account (Name=’ XYZ Pty Ltd’ ));

insert lstAccountToInsert;

delete 1stAccountToInsert;

Also Read – Control Flow Statements in Salesforce Apex

Undelete Statement

When you delete a record, it goes into the Recycle Bin and is kept for 15 days or until it reaches a certain size. Undelete statements can be used to recover a single or list of sObject records from the recycle bin. Use ALL ROWS in the SOQL to retrieve the records from the recycle bin.

Syntax

  • undelete sObject || undelete Id
  • undelete sObject [] || undelete Id []

Example 

//Example 1: Undelete sobject[]

List<Account> 1stAccountToInsert = new List<Account> ( );

1stAccountToInsert.add(new Account (Name=’ABC Pty Ltd’ )) ;

1stAccountToInsert.add(new Account (Name=’XYZ Pty Ltd’ ));

insert 1stAccountToInsert;

delete 1stAccountToInsert;

List<Account> lstAccountsToUndelete = [

SELECT Id FROM Account

WHERE (

Name = ‘ABC Pty Ltd’ OR

Name = ‘XYZ Pty Ltd’

) AND IsDeleted = true

ALL ROWS

];

undelete 1stAccountsToUndelete:

Merge Statement

Up to three records of the same sObject type can be merged into a single record while deleting the others with the Merge command. Related child records are reparented to the master record for the deleted sObject. The master record’s field values take precedence over those of the other records. Merge is not a legitimate trigger event. After a merge statement, delete and update events are fired.

Syntax

  • merge sObject sObject
  • merge sObject sObject []
  • merge sObject Id
  • merge sObject Id []

Example 

/ /Example 1: Merge statement

List<Account> lstAccountToInsert = new List<Account>() ;

1stAccountToInsert.add(new Account (Name=’ABC Private Ltd’, Type= ‘Prospect ‘ )) :

1stAccountToInsert.add(new Account (Name=’ ABC PTY Ltd. ‘ ));

IstAccountToInsert.add(new Account (Name=’ABC pty Limited’ ));

insert lstAccountToInsert;

Account masterSobject = [SELECT Id, Name FROM Account WHERE Name = ‘ABC Private Ltd’ LIMIT 1];

List<Account> lstAccountsToMerge = [

SELECT Id, Name FROM Account

WHERE (

Name = ‘ABC PTY Ltd.’ OR Name = ‘ABC pty Limited’

LIMIT 2

merge masterSobject 1stAccountsToMerge;

Database Methods

Methods based on database class definitions are a more flexible way to work with DML statements than statements based on insert, update, upsert, etc. With database methods, partial updating is possible, unlike with DML statements. A single sObject or a List<sObject> is accepted by each database method. allOrNone specifies whether partial success may be allowed for the operation.

The following are the available Database Methods:

  • Database.insert()
  • Database.update()
  • Database.upsert()
  • Database.delete()
  • Database.undelete()
  • Database.merge()

Insert Operation

Insert operations can be used in Salesforce to create a new or a list of records in a standard or custom object. A collection of SaveResults is returned when using the database method for inserting.

Syntax

  • Database.insert(sObject, allOrNone)
  • Database.insert(sObject [], allOrNone)

Example 

//Example 1: Inserting sObject[] using Database. insert (sobject[], false)

List<Account> lstAccountsToInsert = new List<Account> () ;

1stAccountsToInsert.add(new Account (Name=’ABC Pty Ltd’ ));

1stAccountsToInsert.add(new Account (Name = null, Type = ‘Prospect’ ) );

List<Database.SaveResult> lstSaveResult = Database. insert(1stAccountsToInsert, false) ;

for(

Database.SaveResult eachSaveResult : 1stSaveResult

if (eachSaveResult.isSuccess () ){

System.debug ( ‘Account Id = ‘+ eachSaveResult.getId()) :

}

else‹

for (Database.Error eachError : eachSaveResult.getErrors()){

System.debug (‘Error message = ‘+ eachError-getMessage()) ;

}

//USER_ DEBUG [11] DEBUG Account Id = 0010100002Ywkn4QAB

//USER_DEBUG [15]|DEBUG|Error message = Required fields are missing: [Name ]

Update Operation

Similar to the Update DML statement, the Database.update operation can be used to modify an existing record or a list of records in a standard or custom object.

Syntax

  • Database.update(sObject, allOrNone)
  • Database.update(sObject [], allOrNone)

Example 

/ *

* Example 1: Update sobject[] using Database. update(sobject[], false)

* Inserting new list of sObject – Accounts with name as ‘ABC Pty Ltd’ and ‘XYZ Pty Ltd’

* Updated the created list with Type as Prospect.

* /

List<Account> lstAccounts = new List<Account> () ;

1stAccounts.add (new Account (Name=’ ABC Pty Ltd’ )) ;

1stAccounts.add (new Account (Name=’ XYZ Pty Ltd’ )) ;

insert 1stAccounts;

//update syntax

List<Account> 1stAccountToUpdate = new List<Account> () ;

for (Account eachAccount : lstAccounts) {

eachAccount. Type = ‘Prospect’ ;

1stAccountToUpdate. add (eachAccount) ;

Database.update(1stAccountToUpdate,

false);

Conclusion

Wrapping up, you’ve now got a strong foundation in Apex DML.  Remember, practice is key! Experiment with different DML statements and database methods to truly master these powerful tools.

free salesforce exam voucher

Ready to take your Salesforce skills to the next level? Get hands-on experience and prepare for in-demand certifications with saasguru. Sign up for a free trial and access 18+ Salesforce certification courses, 50+ mock exams, and 50+ interactive labs. 

Start your Salesforce mastery journey today!

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Salesforce Announces Dreamforce 2025: Dates and Key Details

Discover the latest updates on Dreamforce 2025, including dates, location, and what to expect from Salesforce’s premier event. Read now!

Salesforce Named a Leader in 2024 for Multichannel Marketing Hubs

Salesforce recognized as a Leader in 2024 Gartner Magic Quadrant for Multichannel Marketing Hubs, driving personalized, cross-channel engagement.

Salesforce October 2024 Updates by saasguru

Salesforce’s October 2024 updates bring AI innovations, partnerships, and recognitions, driving cloud solutions across industries. Read now!