Sub topic 11
Creating and Inspecting Records in Apex
This chapter covers how Apex code creates, changes and reads records of standard and custom objects. It assumes you know the object, field and relationship concepts from earlier chapters, including __c and __r names. It also assumes you can read basic SOQL and understand Apex syntax such as classes, lists and loops. The examples use the Invoice__c object from earlier in the tutorial. It has a text Name, a lookup Account__c, a number Amount__c and a picklist Status__c.
The working model: sObjects and DML
Apex represents every record as an sObject. Each object in your org gets a matching Apex type: Account, Contact and Invoice__c all work the same way. An sObject instance in memory is only a copy. Nothing reaches the database until you run a DML (Data Manipulation Language) operation on it.
The main DML operations:
| Operation | Effect | Needs an Id |
|---|---|---|
| `insert` | Creates new records and fills in their `Id` | No (it must be empty) |
| `update` | Changes fields on existing records | Yes |
| `upsert` | Inserts or updates, matching on `Id` or an external ID field | Optional |
| `delete` | Moves records to the Recycle Bin | Yes |
| `undelete` | Restores records from the Recycle Bin | Yes |
Each operation has a statement form (insert inv;) and a method form (Database.insert(inv, false);). The statement form throws a DmlException if any record fails. The Database method form lets you choose partial success, which is covered below.
A save moves through several steps inside the platform, and each step can reject the record.
Creating records
Creating a record means building an sObject, setting its fields, and inserting it. You can set fields in the constructor or by assignment. This example creates an account and a linked invoice.
Account acc = new Account(Name = 'Acme Corp');
insert acc;
System.debug('Account Id after insert: ' + acc.Id);
Invoice__c inv = new Invoice__c(
Name = 'INV-0001',
Account__c = acc.Id,
Amount__c = 1200,
Status__c = 'Open'
);
insert inv;
System.debug('Invoice Id after insert: ' + inv.Id);Three details matter here:
- You link records through the lookup field (
Account__c) and give it an Id. The relationship nameAccount__ris for reading parent data in queries. Assigning a value toAccount__rdoes not link anything. insert accmust run before you readacc.Id. Before the insert,Idisnull.- Only the fields you set, plus the
Id, are populated after an insert. System fields such asCreatedDateand formula fields stay empty until you query the record again.
Create many records at once
Always run DML on a list, not inside a loop. Apex enforces governor limits per transaction: at most 150 DML statements and 10,000 DML rows. A loop that runs insert once per record hits the statement limit quickly. A single list insert counts as one statement.
Account acc = new Account(Name = 'Bulk Demo Co');
insert acc;
List<Invoice__c> invoices = new List<Invoice__c>();
for (Integer i = 1; i <= 3; i++) {
invoices.add(new Invoice__c(
Name = 'INV-10' + i,
Account__c = acc.Id,
Amount__c = 100 * i,
Status__c = 'Open'
));
}
insert invoices;
System.debug(invoices.size() + ' invoices inserted');Handle partial failure
With insert invoices;, one bad record makes the whole statement fail and roll back. When you want the good records saved and the bad ones reported, pass false for the allOrNone parameter.
Account acc = new Account(Name = 'Partial Demo Co');
insert acc;
List<Invoice__c> invoices = new List<Invoice__c>{
new Invoice__c(Name = 'INV-201', Account__c = acc.Id, Amount__c = 50, Status__c = 'Open'),
new Invoice__c(Account__c = acc.Id, Amount__c = 75, Status__c = 'Open') // no Name
};
Database.SaveResult[] results = Database.insert(invoices, 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() + ' ' + err.getFields());
}
}
}The result array is in the same order as the input list, so index i identifies the failing record. The second invoice has no Name, so it fails with REQUIRED_FIELD_MISSING while the first one saves.
Changing and removing records
To update a record, set the fields and run update. The record needs a valid Id. The simplest safe pattern is to query the record, change it, and save it. A fresh sObject with only an Id and the changed field also works, and it avoids overwriting other fields.
Invoice__c inv = [SELECT Id, Status__c FROM Invoice__c WHERE Name = 'INV-0001' LIMIT 1];
inv.Status__c = 'Paid';
update inv;Use delete inv; to remove a record. Deleting a parent can also delete or block deleting its children, depending on the relationship type (master-detail children are deleted with the parent). Deleted records stay in the Recycle Bin for 15 days and can be restored with undelete.
Inspecting records
Inspecting means reading values back out. Most of the time you query with SOQL and read fields with dot notation.
List<Invoice__c> rows = [
SELECT Id, Name, Amount__c, Status__c, Account__r.Name
FROM Invoice__c
WHERE Status__c = 'Open'
];
for (Invoice__c row : rows) {
System.debug(row.Name + ' owes ' + row.Amount__c
+ ' to ' + row.Account__r.Name);
}Account__r.Name works because the query asked for it. The parent record arrives as a nested sObject. If Account__c is empty on a row, row.Account__r is null and row.Account__r.Name throws a NullPointerException. Check the parent first, or use the safe navigation operator: row.Account__r?.Name.
The unqueried-field error
Apex only populates the fields you select. Reading any other field throws a runtime error, even though the field exists on the object.
Invoice__c inv = [SELECT Id, Name FROM Invoice__c LIMIT 1];
try {
System.debug(inv.Amount__c);
} catch (System.SObjectException e) {
System.debug('Caught: ' + e.getMessage());
}The message reads SObject row was retrieved via SOQL without querying the requested field. The fix is to add the field to the SELECT list. This differs from a field that was queried but holds no value, which returns null.
Dynamic access
When you do not know the field names at compile time, use get, put and getSObject. They take the API name as a string.
Invoice__c inv = [SELECT Id, Amount__c, Account__r.Name FROM Invoice__c LIMIT 1];
Object amount = inv.get('Amount__c');
String parentName = (String) inv.getSObject('Account__r').get('Name');
System.debug('Amount: ' + amount + ', Account: ' + parentName);
Map<String, Object> populated = inv.getPopulatedFieldsAsMap();
System.debug(populated.keySet());getPopulatedFieldsAsMap() returns only the fields that hold data on that instance. It is useful for debugging when you are unsure what a query returned.
Inspect the object itself
The Schema describe methods tell you about the object, not a single record. This is how you confirm an object is standard or custom, or list its fields.
Schema.DescribeSObjectResult accountDescribe = Account.SObjectType.getDescribe();
Schema.DescribeSObjectResult invoiceDescribe = Invoice__c.SObjectType.getDescribe();
System.debug(accountDescribe.getName() + ' custom? ' + accountDescribe.isCustom());
System.debug(invoiceDescribe.getName() + ' custom? ' + invoiceDescribe.isCustom());
for (String fieldName : invoiceDescribe.fields.getMap().keySet()) {
System.debug(fieldName);
}Describe results also report whether the current user can create or update the object (isCreateable(), isUpdateable()). This leads to security.
Security in Apex
Apex normally runs in system mode. Object permissions and field-level security from permission sets and profiles are not enforced by default, so code can read and write data the running user cannot reach in the UI. Sharing rules are enforced only if the class is declared with sharing.
Recent API versions let you enforce user permissions explicitly:
public with sharing class InvoiceService {
public static List<Invoice__c> openInvoices() {
return [
SELECT Id, Name, Amount__c
FROM Invoice__c
WHERE Status__c = 'Open'
WITH USER_MODE
];
}
public static void markPaid(List<Invoice__c> invoices) {
for (Invoice__c inv : invoices) {
inv.Status__c = 'Paid';
}
Database.update(invoices, AccessLevel.USER_MODE);
}
}In user mode, a query or DML that touches an object or field the user cannot access throws an exception instead of silently succeeding.
Common errors
| Error | Usual cause | Fix |
|---|---|---|
| `REQUIRED_FIELD_MISSING` | A required field, such as the `Name` on `Invoice__c`, was not set | Set the field before the DML |
| `Too many DML statements: 151` | DML inside a loop | Collect records in a list and run DML once |
| `INVALID_FIELD_FOR_INSERT_UPDATE` | Setting a read-only field such as a formula field, or setting `Id` on an insert | Remove the field |
| `SObject row was retrieved via SOQL without querying the requested field` | Reading a field that was not in the `SELECT` list | Add the field to the query |
| `NullPointerException` on `Account__r.Name` | The lookup is empty | Check for `null` or use `?.` |
| `FIELD_CUSTOM_VALIDATION_EXCEPTION` | A validation rule rejected the record | Fix the data, or review the rule |
| `INSUFFICIENT_ACCESS_OR_READONLY` | The user cannot edit the record, or user-mode DML lacks access | Review sharing and permissions |
Summary
Apex treats every record as an sObject that exists only in memory until DML saves it. Run DML on lists to stay inside governor limits, and use the Database methods when you need partial success. Query exactly the fields you plan to read, including parent fields through __r. Use describe calls to inspect the object. Choose system mode or user mode deliberately.
Exercise
A trigger-free script loops over 200 Invoice__c records, sets Status__c = 'Paid' on each, and calls update inv; inside the loop. It fails partway through. What error do you expect, and how do you change the code so it works and still reports which records failed?
Show answer
The script hits the limit of 150 DML statements per transaction and throws "Too many DML statements: 151". Change the loop so it only sets the field and adds each record to a List<Invoice__c>. After the loop, call Database.update(list, false) once. That uses one DML statement. Then loop over the returned Database.SaveResult[], and for each result where isSuccess() is false, read getErrors() to report the problem. The result at index i matches the record at index i in the list.
Exercise
This code throws an exception at the last line. Name the exception, explain why, and give the fix. Invoice_c inv = [SELECT Id, Name FROM Invoicec LIMIT 1]; Decimal total = inv.Amount_c;
Show answer
It throws System.SObjectException. The query selected only Id and Name, so Amount__c was never loaded into the sObject, and Apex refuses to read a field that was not queried. The fix is to add Amount__c to the SELECT list: SELECT Id, Name, Amount__c FROM Invoice__c LIMIT 1. If the field were queried but empty, the result would be null and no exception would occur.