Sub topic 9
Formula fields in SOQL and Apex
This chapter assumes you can write basic SOQL queries and Apex, and that you have already built a formula field. Here you will see how code reads formula fields and why code cannot write them.
Reading formula fields in SOQL
A formula field is queryable like any other field. Salesforce evaluates it when the record is read, so the value is always current. Suppose Opportunity has the Text formula field Size__c from earlier in this tutorial:
List<Opportunity> large = [
SELECT Id, Name, Amount, Size__c
FROM Opportunity
WHERE Size__c = 'Large'
ORDER BY Name
];
for (Opportunity o : large) {
System.debug(o.Name + ' is ' + o.Size__c);
}You can use a formula field in SELECT, WHERE, and ORDER BY. Formula fields that traverse relationships work too. The value reflects the related record's current data.
Formula fields are read-only in DML
You cannot set a formula field or a roll-up summary field in an insert or update. Code that assigns one does not compile, because the field is not writeable. Salesforce calculates the value, so the in-memory record does not contain it after DML. To read the calculated result, query the record again:
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);Without the re-query, inv.Total_Amount__c would be null. The same applies after an update. The variable you hold keeps the old value until you query again.
Triggers and formula values
In a before insert trigger, formula fields on Trigger.new have no values yet, because the record has not been saved. Do not base logic on them there. If an after trigger needs a formula result, query the records by Id. If the value only depends on fields already in the record, repeat the logic in Apex instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Compile error "Field is not writeable" | Assigning a formula or roll-up field | Remove the assignment. Change the source fields instead. |
| Formula value is `null` after `insert` | The in-memory record was not refreshed | Re-query by Id |
| Slow query filtering on a formula | Formula fields are not indexed | Filter on the underlying fields |
Exercise
A developer inserts an Opportunity and then logs opp.Size__c, where Size__c is a formula field. The log shows null. Why, and how do they fix it?
Show answer
The insert saves the record, but the in-memory variable does not receive calculated values. Formula fields are evaluated by Salesforce when the record is read. The fix is to query the record again, for example [SELECT Size__c FROM Opportunity WHERE Id = :opp.Id], and read the field from the result.