Salesforce Decode
Salesforcedecode
Back to questions
ApexIntermediateperformancesoqltriggers

Optimize trigger SOQL with lazy relationship query pattern

Real World Scenario

Order trigger always queries Account, Pricebook, and Owner data even when only Ship_Date__c changes on update.

Expected Answer

• Compare Trigger.oldMap to Trigger.new for field-level change detection • Skip Account query branch if no field depending on Account changed • Utility method: changedFields(records, oldMap) returns Set<String> • Single consolidated query per required object when branch executes • Cache query results in static Map for same-transaction recursion • Profile CPU reduction after lazy load in debug log comparison • Test both full-field update and single-field update code paths

Follow-Up Questions & Answers

Click to expand — each follow-up includes a direct, interview-ready answer

Direct answer: Compare Trigger.oldMap to Trigger.new for field-level change detection Also consider: Skip Account query branch if no field depending on Account changed In practice: Utility method: changedFields(records, oldMap) returns Set<String> Balance speed of delivery with maintainability.

Architect Perspective

Conditional SOQL is free performance—always ask which fields actually changed.