Sub topic 2
Reading Fields from Related Records
Assume you know Salesforce objects, fields, records, and lookup and master-detail relationships. This chapter focuses on how calculated fields cross those relationships and how roll-ups aggregate child records.
Reading fields from related records
A formula field can follow a relationship with dot notation. On an Opportunity, Account.Owner.Name reads the name of the Opportunity’s Account owner.
Account.Owner.NameIf the relationship is blank, the result can also be blank. Cross-object formulas are read-only. They calculate when Salesforce evaluates the record rather than storing an independently editable value.
Working with dates and times
TODAY() returns the current date. NOW() returns the current date and time. Date arithmetic returns a number of days.
CloseDate - TODAY()A positive result means the close date is in the future. A negative result means it has passed. Date/time values may require conversion before comparison with a date, and time-zone behavior matters when users work in different regions.
Formula size and relationship limits
Formula fields have limits on compiled size, referenced fields, and relationship traversal. A formula can also fail when it references unsupported field types or creates a circular dependency. Keep formulas readable by splitting repeated logic into helper fields. Check the formula editor’s compiled-size warning rather than relying only on the number of visible characters.
Formula fields in SOQL and Apex
Formula values are queryable like other fields, but they cannot be assigned in DML. Roll-up values have the same read-only behavior.
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);Re-query after saving when code needs the calculated value.
Why roll-ups need a master-detail relationship
A roll-up summary field stores an aggregate on a master record. Native roll-ups require a master-detail relationship because Salesforce controls the child’s ownership and lifecycle through the master. A lookup relationship does not provide that same structure.
Creating COUNT, SUM, MIN, and MAX roll-ups
Create the field on the master object and select the detail object. Then choose:
COUNTto count detail records.SUMto total a number or currency field.MINto find the smallest value.MAXto find the largest value.
Filter criteria restrict which detail records participate. For example, an Invoice roll-up can sum Line_Item__c.Amount__c only when Is_Billable__c is true.
Exercise
Which native roll-up type should count the number of qualifying line items on an invoice?
Show answer
COUNT.