DML Operations & Transactions in Apex

Share

DML Operations: insert, update, upsert, delete, undelete

What Is DML?

DML (Data Manipulation Language) is used to change data in Salesforce.

Simple Explanation

DML is how you save, edit, or remove records in Salesforce.


Common DML Operations

insert – Create new records

Account acc = new Account(Name = 'ABC Ltd');
insert acc;

update – Modify existing records

acc.Name = 'ABC Corporation';
update acc;

upsert – Insert or update

upsert acc;

Salesforce decides whether to insert or update.


delete – Remove records

delete acc;

undelete – Restore deleted records

undelete acc;

Real-Life Example

Like working with files:

  • insert → create file

  • update → edit file

  • delete → move to recycle bin

  • undelete → restore file


Gist (Quick Revision)

DML operations let you create, modify, remove, and restore Salesforce records.


Database Methods

What Are Database Methods?

Database methods provide more control than standard DML.

Why Use Them?

  • Handle errors gracefully

  • Support partial success

  • Avoid full transaction failure


Example: Database.insert

Database.SaveResult sr = Database.insert(acc, false);

false → allow partial success


Bulk Insert Example

List<Account> accounts = new List<Account>();
Database.insert(accounts, false);

Gist (Quick Revision)

Database methods give better control and error handling than standard DML.


Partial Success Handling

What Is Partial Success?

Partial success means:

Some records succeed, others fail—but the transaction continues.


Real-Life Example

Sending emails:

  • 8 succeed

  • 2 fail
    The process still completes.


Code Example

Database.SaveResult[] results = Database.insert(accounts, false);

for (Database.SaveResult sr : results) {
    if (!sr.isSuccess()) {
        System.debug(sr.getErrors()[0].getMessage());
    }
}

Why This Matters

  • Prevents full rollback

  • Improves user experience

  • Essential for bulk operations


Gist (Quick Revision)

Partial success allows bulk operations without full failure.


Savepoints & Rollback

What Is a Savepoint?

A savepoint marks a point in a transaction where you can roll back.

Simple Explanation

Like a checkpoint in a game—you can return if something goes wrong.


Code Example

Savepoint sp = Database.setSavepoint();

try {
    insert acc;
} catch (Exception e) {
    Database.rollback(sp);
}

When to Use Savepoints

  • Complex business logic

  • Multiple DML operations

  • Need controlled rollback


Gist (Quick Revision)

Savepoints allow safe rollback during failures.

  • January 6, 2026