Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท SOQL and DML

DML: Insert, Update, Delete and Undelete

Save data with Apex DML statements insert, update, upsert, delete and undelete, bulk lists, Database methods with partial success and error handling, with stand-ins.

SOQL reads data; DML (Data Manipulation Language) changes it. DML statements are part of Apex itself: you write insert, update, upsert, delete, undelete and merge directly, with no SQL strings and no connection to open. This lesson covers each one, the bulk-friendly style Salesforce demands, and how to handle failures.

DML needs a real org. Real Apex is shown read-only; the runnable examples are Java stand-ins that model an in-memory table, including what happens to a failed batch.

The basic statements

Java
Account acc = new Account(Name = 'Acme', Industry = 'Energy');
insert acc;                      // creates the record; acc.Id is now set

acc.Industry = 'Technology';
update acc;                      // saves the change (the record needs an Id)

delete acc;                      // moves it to the Recycle Bin
undelete acc;                    // restores it from the Recycle Bin
  • insert creates records and fills in their Ids.
  • update changes existing records. They must have an Id and you must change fields on a record you queried or already inserted.
  • upsert inserts or updates based on a key. With an External Id field: upsert accounts External_Key__c; With no field, it matches on Id.
  • delete soft-deletes into the Recycle Bin; undelete brings it back; Database.emptyRecycleBin removes it permanently.
  • merge combines up to three duplicate Accounts, Contacts or Leads into one.

Always use lists

Each DML statement counts toward the limit of 150 per transaction, no matter how many records it touches (up to 10,000 rows in total). So work with lists:

Java
List<Account> toCreate = new List<Account>();
for (Integer i = 0; i < 200; i++) {
    toCreate.add(new Account(Name = 'Bulk Account ' + i));
}
insert toCreate;          // 1 DML statement for 200 records

Doing insert inside the loop would use 200 statements and exceed 150. Collect records first, then save once after the loop.

flowchart LR
    L["Loop: build records"] --> LIST["List of records"]
    LIST --> D["ONE insert/update<br/>statement"]
    D --> DB[("Database")]

Collect inside the loop; write once after it.

All or nothing

By default, a DML statement on a list is atomic: if any record fails (for example a required field is missing), the whole statement fails with a System.DmlException and none are saved. Here is a Java stand-in for that behaviour.

Java Stand-in (Java): atomic DML on a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Partial success with Database methods

The Database class gives you the same operations with an extra flag, allOrNone. Set it to false and valid records are saved while the failed ones are reported, without throwing:

Java
List<Account> accounts = new List<Account>{
    new Account(Name = 'Good Co'),
    new Account()                         // missing required Name
};

List<Database.SaveResult> results = Database.insert(accounts, false);
for (Integer i = 0; i < results.size(); i++) {
    if (results[i].isSuccess()) {
        System.debug('Saved ' + results[i].getId());
    } else {
        for (Database.Error err : results[i].getErrors()) {
            System.debug('Row ' + i + ' failed: ' + err.getStatusCode() + ' ' + err.getMessage());
        }
    }
}

Results come back in the same order as the input. Other methods: Database.update, Database.upsert (returns UpsertResult), Database.delete (DeleteResult), and Database.undelete.

Which to choose?

Style Use when
insert list; Everything must succeed or nothing should be saved
Database.insert(list, false) A bad row should not block good ones (data loads, integrations)

Here is a stand-in for partial success.

Java Stand-in (Java): partial success results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Catching DmlException

A normal DML statement throws DmlException; catch it to show a friendly message or log the issue:

Java
try {
    insert accounts;
} catch (DmlException e) {
    for (Integer i = 0; i < e.getNumDml(); i++) {
        System.debug(e.getDmlIndex(i) + ': ' + e.getDmlMessage(i));
    }
}

Transactions and rollback

Everything in a transaction is committed together at the end. If an unhandled exception occurs, all DML in the transaction is rolled back. For finer control, use a savepoint:

Java
Savepoint sp = Database.setSavepoint();
insert acc;
// something goes wrong...
Database.rollback(sp);      // undo the insert

Savepoints count toward DML limits and are mostly used in tests and carefully written services.

Things that are easy to forget

  • You cannot mix DML on "setup" objects (like User) and ordinary objects in one transaction without an async hop (a MIXED_DML_OPERATION error).
  • A trigger on an object may run when you do DML, which may do more DML; all share the same limits.
  • delete is reversible for 15 days; permanent deletion is a separate step.
  • To update a queried record, change fields on the object from the query: do not create a new instance with only the Id unless you only mean to change specific fields.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many DML statements does inserting a list of 200 accounts use?

    A DML statement counts once regardless of the list size (up to 10,000 rows).
  2. 2. What does Database.insert(list, false) do when one record is invalid?

    allOrNone = false permits partial success; check each SaveResult.
  3. 3. Which statement restores a deleted record from the Recycle Bin?

    undelete brings records back from the Recycle Bin.
  4. 4. What happens by default if one row in an insert list fails?

    Default DML is all-or-nothing and throws System.DmlException.

Summary

  • DML statements are insert, update, upsert, delete, undelete and merge.
  • Operate on lists, outside loops; one statement counts once toward the 150 limit.
  • Default DML is atomic and throws DmlException; Database methods with allOrNone=false allow partial success.
  • Transactions roll back on unhandled errors; savepoints give manual control.

Next: Trigger Basics