3

Like AccountName vs Account.Name. The first being a formula field, and the second one a relationship.

Since formula fields are like Schrödinger's Cat (the value depends on the time you are getting its value), I suppose there is a query on the background. My doubt is whether it is faster than a direct relationship query.

6

If the formula is literally:

Account.Name

Then you get the use of indexes, such that:

WHERE AccountName__c = 'Demo'
WHERE Account.Name = 'Demo'

Are identical in performance.

Formula Using Index

If you use any sort of formula function, it reverts to a TableScan, resulting in a massive performance drop:

BLANKVALUE(Account.Name, '--None--')

Formula Not Using Index

In the first formula, your users will not likely experience timeouts from queries being too complicated (e.g. non-selective query errors), but in the latter, your users may experience performance problems (longer query execution time and/or non-selective query errors).

  • Is it good practice to use formulas instead of querying relationship field. Lets say in Trigger, if I want to refer parentAccount's name on the Account I am working on, if I just use formula i will save SOQL.. as I have an unlimited license so having 800 fields and creating formula fields helps me save a bunch of queries. If formulas are simple it wont have any performance implications? – Pranay Jaiswal May 14 '18 at 13:54
  • 4
    @PranayJaiswal There's a trade off to using formulas this way, and it's nothing to do with performance. When you create formulas just to pull in data from a related record, it makes code maintenance more challenging. I would recommend doing this only as a last resort (e.g. you're already at the governor limit) and document it clearly. There's nothing more frustrating than having to look in Setup while reading code. – sfdcfox May 14 '18 at 14:00
2

It's a bit difficult to provide a blanket answer, but there are some techniques you can use to write more efficient queries. There is a good Trailhead module detailing such practices.

Additionally, Salesforce provides a great tool via their dev tool called Query Plan which allows you to compare the actual "cost" of queries against each other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.