Sub topic 9
Formula Fields in SOQL and Apex
This chapter assumes you can create a formula field, know the basic SOQL SELECT and WHERE syntax, and can read short Apex classes. It covers how formula fields (and roll-up summary fields) behave when code reads them, and the mistakes that follow from that behavior.
What code sees
A formula field is calculated when a record is read. Salesforce does not store the result in the same way it stores a text or number field. Your code treats it as a normal field when it reads it, but two rules apply:
- You can read formula fields in SOQL and Apex.
- You cannot write to them. A formula field is read-only, and so is a roll-up summary field.
Roll-up summary fields follow the same read-only rule in code. They are stored on the master record and recalculated by the platform when child records change. You still cannot assign a value to them in DML.
| Behavior | Formula field | Roll-up summary field |
|---|---|---|
| Readable in SOQL and Apex | Yes | Yes |
| Writable in DML | No | No |
| Value is computed | When the record is read | When child records change |
| Appears in `SELECT` | Yes | Yes |
Reading formula fields in SOQL
You select a formula field by its API name, like any other field. Cross-object formulas work the same way, because the formula does the traversal for you.
SELECT Id, Name, Amount FROM Opportunity WHERE Id = :oppIdIf the Opportunity has a Text formula field called Size_Label__c, you add it to the SELECT list:
SELECT Id, Name, Size_Label__c FROM Opportunity WHERE Id = :oppIdYou can filter on a formula field in a WHERE clause. This works, but it has a cost. Salesforce cannot use an index on most formula fields, so the filter can force a full scan of the object. On large objects this makes queries slow, and it can cause "non-selective query" errors in triggers. Where possible, filter on the underlying stored fields instead.
SELECT Id FROM Opportunity WHERE Size_Label__c = 'Large'The equivalent filter on stored fields is usually faster:
SELECT Id FROM Opportunity WHERE Amount > 100000Formula fields can also appear in ORDER BY and in some aggregate queries, with the same performance concern.
Reading formula and roll-up values in Apex
When a query returns a record, the formula value is a property of the sObject like any other field. The key point is timing: a formula or roll-up value only exists after the record has been saved and queried back. A record you build in memory has no calculated value.
This code inserts an invoice and re-queries it to get the roll-up value.
Invoice__c inv = new Invoice__c(Name = 'INV-001');
insert inv;
Invoice__c saved = [SELECT Id, Total_Amount__c FROM Invoice__c WHERE Id = :inv.Id];
System.debug(saved.Total_Amount__c);After insert inv, the variable inv does not hold Total_Amount__c. Reading inv.Total_Amount__c returns null. The re-query fetches the value from the database.
The same applies after an update. If your code changes Amount on an Opportunity, the in-memory record still shows the old value of any formula that depends on Amount, until you query the record again.
Writing to a calculated field fails
Trying to set a formula or roll-up field is a compile-time error when the field is referenced directly in Apex:
Opportunity opp = new Opportunity();
opp.Size_Label__c = 'Large'; // Compile error: field is not writeableIf you build records dynamically with put(), the failure happens at runtime instead. The result is a SObjectException saying the field is not writeable. Both errors have one fix: set the underlying fields and let the formula recalculate.
Formula values in triggers
Triggers add a wrinkle. In a before trigger, records in Trigger.new have not been saved, so formula fields hold no reliable value for the new data. In an after trigger, the formula values on Trigger.new records can be read, but they reflect the saved data. For a safe result in either case, re-query the records you need, or compute the value from the stored fields.
For roll-up summary fields, the master record's roll-up value changes after the child DML completes. A trigger on the child object that reads the master's roll-up value sees the old value, because the platform recalculates it later in the order of execution.
sequenceDiagram
participant Code as Apex code
participant DB as Database
participant Calc as Platform calculation
Code->>DB: insert Line_Item__c
DB->>Calc: child saved, recalculate roll-up
Calc->>DB: update Invoice__c.Total_Amount__c
Code->>DB: SOQL on Invoice__c
DB-->>Code: returns the new Total_Amount__cNote that the fence above is written with the diagram mermaid form in the final chapter output; the sequence is what matters: query after the save.
Aggregate queries over formula fields
Aggregate functions in SOQL work on stored numeric fields. Support for formula fields in aggregates is limited and depends on the return type, so test your specific query before relying on it. For totals across child records, a roll-up summary field or an AggregateResult query on stored fields is the more dependable choice.
This snippet sums a stored field per account. It is the same pattern used for manual roll-ups on lookup relationships.
public static void recalculateTotals(Set<Id> accountIds) {
Map<Id, Account> toUpdate = new Map<Id, Account>();
for (Id accId : accountIds) {
toUpdate.put(accId, new Account(Id = accId, Total_Payments__c = 0));
}
for (AggregateResult ar : [
SELECT Account__c acct, SUM(Amount__c) total
FROM Payment__c
WHERE Account__c IN :accountIds
GROUP BY Account__c
]) {
Id accId = (Id) ar.get('acct');
toUpdate.get(accId).Total_Payments__c = (Decimal) ar.get('total');
}
update toUpdate.values();
}The code first sets every account's total to 0, so accounts with no payments are reset. It then overwrites the total for accounts that have payments. Here Total_Payments__c is a regular number field, so the update is allowed.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Formula field is `null` after `insert` | Value was never queried back | Re-query the record by Id |
| "Field is not writeable" | Assigning to a formula or roll-up field | Write the source fields instead |
| Stale formula value after an update | In-memory record not refreshed | Re-query after DML |
| Slow or non-selective query | Filtering on a formula field | Filter on indexed, stored fields |
| Roll-up value looks old in a child trigger | Recalculation happens after child save | Query the master after the DML completes |
Practical guidance
- Treat formula and roll-up values as outputs. Read them after saving, and never try to set them.
- Re-query the record when you need a fresh calculated value.
- Avoid formula fields in
WHEREclauses on large objects. Filter on stored fields that match the formula's logic. - If code needs a value to be stored, filtered quickly, or set by code, use a regular field populated by Flow or Apex.
Exercise
An Apex method inserts an Invoice_c, then logs inv.TotalAmount__c, a roll-up summary field. The log shows null even though line items exist. What are two reasons, and what should the method do?
Show answer
The in-memory record never received the calculated value, because roll-up and formula values are computed by the platform and are not copied back into the variable after insert. Also, line items inserted after the invoice may not have been saved yet, so the roll-up has nothing to total. The method should save the line items, then re-query the invoice by Id with SELECT Id, TotalAmount_c and read the value from the result.
Exercise
A developer writes opp.SizeLabelc = 'Large'; in Apex, where SizeLabel__c is a formula field. What happens, and how should the developer get the label 'Large'?
Show answer
The code fails to compile because formula fields are not writeable. To get 'Large', set Amount to a value above 100000 and save. Then query SizeLabel_c to read the calculated result.