Skip to content
Namaste Salesforce Namaste Salesforce
Developer Roadmap

SOQL & DML

Read data with SOQL and change it with DML — efficiently, in bulk, and within governor limits.

Developer Roadmap Article 1 min

SOQL & DML

Apex talks to the database in two directions. SOQL (Salesforce Object Query Language) reads records, and DML (Data Manipulation Language) creates, updates, and deletes them. Using both efficiently, in bulk, and within governor limits is the difference between code that survives a data load and code that fails at 200 records.

SOQL looks like SQL but only queries one primary object at a time, traversing relationships by name. You embed queries directly in Apex, and Apex variables are referenced with a colon (a bind variable), which is also how you stay safe from injection.

Set<Id> acctIds = new Set<Id>{ '001...', '001...' };

// Child-to-parent (dot) and parent-to-child (subquery) in one query
List<Account> accts = [
    SELECT Id, Name, Owner.Name,
           (SELECT Id, Email FROM Contacts)
    FROM Account
    WHERE Id IN :acctIds          // bind variable, injection-safe
    ORDER BY Name
    LIMIT 200
];

// Collect changes, then DML once (bulk-safe)
List<Contact> toUpdate = new List<Contact>();
for (Account a : accts) {
    for (Contact c : a.Contacts) {
        c.Description = 'Reviewed';
        toUpdate.add(c);
    }
}
update toUpdate;   // one DML statement for all contacts

Two relationship patterns matter. Child-to-parent uses dot notation (Owner.Name) to walk up. Parent-to-child uses a subquery with the child relationship name (Contacts). Learning the relationship names — and that custom relationships use __r — unlocks efficient single-query data retrieval.

The DML operations are insert, update, upsert, delete, and undelete. The cardinal rule from the limits lesson applies here: query before loops and DML after them, always on lists. Wrapping DML in Database methods (for example Database.update(records, false)) lets you allow partial success and inspect per-record results, which is valuable for bulk jobs.

As an exercise, write a method that queries Accounts with their Contacts, stamps a field on each contact, and updates them all in a single DML. Confirm with Limits.getQueries() that you used exactly one query and one DML regardless of record count. Next we apply SOQL and DML inside triggers using a maintainable handler pattern.

Advertise with us · 728×90