SOQL has two ways to filter on a calculated value. You can put a formula field in the WHERE clause (it works in every org, but it is evaluated for each record and has no index unless Salesforce Support adds one to a deterministic formula), or, as of Winter '27, use the FORMULA() function, which is in beta, needs API version 68.0 and isn't available in production orgs. It compares two fields with + or -, such as WHERE FORMULA('Amount - ExpectedRevenue') > 100.
SOQL is how most Apex code gets data out of Salesforce (see SOQL vs SOSL for when search fits better), and most filters hit plain stored fields. This post covers both calculated-value options, what each one costs, and when I would skip both and filter in Apex. For the rest of the query language, start with the SOQL complete guide.
FORMULA() in the SOQL WHERE clause (Winter '27 beta)
SOQL has never let you compare one field with another. WHERE Amount > ExpectedRevenue is rejected because the right side of a comparison has to be a literal or a bind variable. FORMULA() covers part of that gap. The shape is:
WHERE FORMULA('<field> <+|-> <field>') <comparisonOperator> <literal>
The rules, from the FORMULA() reference:
- It goes in the
WHEREclause only. It isn't supported inSELECT, and the Summer '26 pilot announcement said it was supported inWHEREand not inHAVING. - The expression takes two fields and one operator, which must be
+or-. - The comparison operator is
>,<,=,>=,<=or!=, and the result is compared to a literal. - Supported field types are Double/Decimal, Integer, DateTime, Date and Currency.
- You can't mix Date and DateTime in one expression. If the left-hand field isn't a date type, the right-hand field can't be one either.
- No other formula functions are available, so
IF,TODAY()and the rest of the formula language stay in formula fields.
Salesforce publishes these two examples:
SELECT Id, Name FROM Opportunity WHERE FORMULA('Amount - ExpectedRevenue') > 100
SELECT Id, Name, Revenue__c, Cost__c FROM Order__c WHERE Status__c = 'Shipped' AND FORMULA('Revenue__c - Cost__c') > 250
Copy the shape of the second one. A normal filter on Status__c cuts the rows down first, and the computed comparison runs on what is left.
Summer '26 ran FORMULA() as a pilot open to any customer, with ISVs who can't add formula fields to a subscriber's schema as one of the main use cases. Winter '27 moved it to beta. It requires API version 68.0 and isn't available in production orgs, so try it in a sandbox or a scratch org. It is a beta service under the Beta Services Terms, and the syntax or behaviour can still change before GA.
Until it is GA in production, keep a formula field or an Apex filter for production code. I use the beta to prototype the query I'll want later and to see whether the computed filter narrows the rows enough to justify switching. In a managed package, ship the Apex filter now and plan the swap for after GA. You maintain two versions of the logic for a release or two, which costs less than shipping a dependency on a beta.
Formula field vs FORMULA() vs filtering in Apex
| Formula field in WHERE | FORMULA() in WHERE | Filter in Apex | |
|---|---|---|---|
| Available in production | Yes | No (beta, non-production orgs only) | Yes |
| Needs schema change | Yes, a field | No | No |
| Logic supported | Full formula language, cross-object | + and - on two fields only |
Anything |
| Indexable | Only deterministic formulas, via a Support-created custom index | Not documented, treat as unindexed | n/a, filter after the query |
| Counts against query rows | Only matching rows returned | Only matching rows returned | Every row the broader query returns |
| Best for | Stored logic reused in reports and list views | Ad-hoc two-field comparisons, ISV packages that can't add fields | Complex or dynamic rules |
In the Apex option, every row the broader query returns counts against the 50,000-row governor limit, including the rows you throw away in the loop.
When to use formula fields in WHERE clauses
A formula field calculates its value from other fields, expressions and cross-object references when the record is read. Nothing is stored on the row. That makes it tempting in a WHERE clause, because the filter can depend on logic instead of static data, and reports, list views and page layouts can reuse the same logic.
Formula fields in WHERE earn their keep in these cases:
- A formula turns dates and picklists into a derived status such as 'Overdue', 'At Risk' or 'On Track', and you query on that status.
- The filter depends on a calculation that reads fields on a parent record, within the cross-object relationship limit.
- You compare against a calculated value you can't practically store, such as
LastActivityDate__cagainstCloseDate__cplus a number of days the formula works out. - Simple filtering that would otherwise be an Apex loop can live in the query instead.
- Two-field arithmetic comparisons can now use
FORMULA()in non-production orgs, so once it reaches production you may not need a new field just to compareRevenue__cwithCost__c.
Take an Opportunity with a Probability_Score__c formula that scores stage, amount and some custom probability fields. To find everything above 0.7:
SELECT Id, Name, Probability_Score__c
FROM Opportunity
WHERE Probability_Score__c > 0.7
That query is short and runs in every org on every API version. Whether it stays fast depends on the next section.
Indexing, selectivity and the query plan
Salesforce calculates a formula in a WHERE clause for every record the query considers. A complex formula costs more per record, and data volume multiplies that cost.
Formula fields have no index by default. Salesforce Customer Support can add a custom index to a deterministic formula field. A formula that uses TODAY()/NOW() or reaches fields on related objects is non-deterministic and can't be indexed (SOQL Best Practices: Nulls and Formula Fields), and every index adds maintenance work on DML (Formula Fields, Indexes, and Performance Gotchas). That maintenance runs on every insert or update that touches a field the formula references, so bulk loads slow down too. On an object with more than a million records, an unindexed formula filter can force a full scan. The post on managing large data volumes in Salesforce explains the selectivity thresholds behind that.
A non-deterministic formula also hides the index on the field underneath it. If a Days_Since_Close__c formula is built on TODAY() - CloseDate, filtering on it means the optimizer never considers the index on CloseDate (same 2013 Gotchas blog). Writing the logic directly in the filter can be faster on objects with more than a million records. In Apex, calculate the date boundaries and bind them:
// Replaces: WHERE IsWon = true AND Days_Since_Close__c >= 14 AND Days_Since_Close__c <= 21
Date followUpFrom = Date.today().addDays(-21);
Date followUpTo = Date.today().addDays(-14);
List<Opportunity> wonDealsForReview = [
SELECT Id, Name, CloseDate, OwnerId
FROM Opportunity
WHERE IsWon = true
AND CloseDate >= :followUpFrom
AND CloseDate <= :followUpTo
];
This returns the same opportunities as the formula filter, but the optimizer gets a plain date range on CloseDate and can consider its index. I have seen this one change fix a trigger that kept failing with the non-selective query error on a large Opportunity table.
To see what a query is doing, check its plan. As of Winter '27, Developer Console no longer appears in the Setup menu by default. Build queries in Web Console's SOQL Builder and check their query plans there, or re-enable Developer Console from Setup > Web Console > Enable Developer Console (Winter '27 developer guide). In practice that means searching Quick Find for Development, selecting Web Console and setting Enable Developer Console to Active. Running queries in Web Console requires the Use Any API Client user permission. The plan won't name a formula field, but the operation types tell you enough: TableScan on a large object means no index carried the filter, and Index means one did.
The Full_Name__c pitfall
Take a Full_Name__c formula that joins FirstName__c and LastName__c:
SELECT Id, Name
FROM Contact
WHERE Full_Name__c = 'John Doe'
This looks cheap. On a Contact object with millions of records it isn't, because Full_Name__c is calculated for every one of them. Where you can, filter on FirstName__c and LastName__c separately, or fetch a narrower set and filter it in Apex. SOQL can't compare one field to another in a plain WHERE expression, which is why people reach for formula fields, and FORMULA() is the beta alternative. It only accepts numeric, currency and date fields, though, so it won't help with a text match like this one.
If the logic has to come from the formula, or the object is small enough that nobody will notice, filtering on the formula field directly is still the practical choice.
Best practices for formula fields in queries
Keep the formula simple. The simpler it is, the cheaper each evaluation. Avoid deeply nested
IFstatements, heavy date manipulation and long text concatenation where you can. If a formula is genuinely complex, consider moving part of the logic into a trigger or flow that writes a stored field, which you can index.Filter on the underlying fields first. If the formula depends on other fields, add those fields to the
WHEREclause too, so fewer records reach the formula evaluation.Instead of
WHERE Derived_Status__c = 'Urgent', whereDerived_Status__cdepends onPriority__candDueDate__c, tryWHERE Priority__c = 'High' AND DueDate__c < TODAY AND Derived_Status__c = 'Urgent'. How much it helps depends on indexing and data distribution, but the pattern is worth trying. Note the date literal:TODAYtakes no parentheses in SOQL.TODAY()is formula and Apex syntax, and the query won't parse with it.Watch data skew and selectivity. A condition as broad as
WHERE Some_Formula_Field__c != ''scans a large share of your data. Write conditions that actually narrow the result set.Use Apex for complex filtering and large data volumes. Query on stored fields, then filter the results in Apex.
List<Account> accountsToProcess = [SELECT Id, Name, Custom_Metric__c FROM Account WHERE AnnualRevenue > 1000000]; List<Account> filteredAccounts = new List<Account>(); for (Account acc : accountsToProcess) { // Custom_Metric__c is a formula field if (acc.Custom_Metric__c != null && acc.Custom_Metric__c > 50) { filteredAccounts.add(acc); } } // Process filteredAccountsYou pay for the rows you discard, and that can still come out ahead when the
AnnualRevenuefilter is highly selective.Test with real data. Use realistic volumes and distributions in a sandbox, check the query plan in Web Console, and record execution times. Include the edge cases and the odd records.
Track the cross-object limit. Formula fields built on lookups or master-detail relationships count towards the 15 unique cross-object relationships per object. If you go over it, you can't create or save the formula field at all.
Combining filters, aggregates and the Apex fallback
A formula field combined with standard or indexed fields works well. The optimizer can use the indexed condition to cut down the records before the formula is evaluated:
SELECT Id, Name, Opportunity.CloseDate, Opportunity.Days_Until_Close__c
FROM OpportunityLineItem
WHERE Opportunity.CloseDate = THIS_QUARTER
AND Opportunity.Days_Until_Close__c < 7
Days_Until_Close__c is a formula field on Opportunity. The condition on Opportunity.CloseDate can use an index, and the formula condition applies to what is left.
Formula fields also work in aggregate queries, with the same performance caveats plus one more:
SELECT COUNT(Id), CreatedMonth__c
FROM CustomObject__c
GROUP BY CreatedMonth__c
HAVING COUNT(Id) > 10
CreatedMonth__c pulls the month out of CreatedDate. A field can only appear in GROUP BY if its describe reports it as groupable (Schema.DescribeFieldResult.isGroupable()), and many formula fields aren't. Check that for CreatedMonth__c first:
Schema.DescribeFieldResult monthDescribe = Schema.SObjectType.CustomObject__c.fields.CreatedMonth__c;
System.debug('CreatedMonth__c groupable: ' + monthDescribe.isGroupable());
If it isn't groupable, group on CALENDAR_MONTH(CreatedDate) and skip the formula altogether:
SELECT CALENDAR_MONTH(CreatedDate) m, COUNT(Id) FROM CustomObject__c GROUP BY CALENDAR_MONTH(CreatedDate) HAVING COUNT(Id) > 10
To sort aggregate results, the SOQL ORDER BY guide covers ordering by aliases and aggregate functions.
Some filters are beyond SOQL with or without formula fields: a threshold decided at runtime by user input, complex formula logic buried in a subquery where it gets slow and hard to read, or a calculation too heavy for a formula field to carry. Fetch a broader set with a simpler SOQL query and do the real filtering in Apex. The code is longer, but you can see exactly what it costs and change it without touching the schema.
What to watch for
- A single object can have a maximum of 15 unique cross-object relationships across all its formula fields. If your formula relies on relationships, that ceiling is global per object.
- Plan as if a formula filter is unindexed. A custom index needs Support, a deterministic formula and a tolerance for extra DML overhead.
- Match the comparison to the formula's return type. Comparing a text formula with a numeric literal fails or behaves in ways you won't expect.
FORMULA()needs API version 68.0 and won't run in production orgs as of Winter '27. Code saved at an older API version can't use it, and Salesforce doesn't document whether it can use an index.FORMULA()can't mix Date and DateTime, and a non-date left-hand field rules out a date right-hand field, soFORMULA('Amount - CloseDate')is rejected.- If your team's runbooks say to open Developer Console from Setup, update them for Web Console or re-enable the console.
FAQ
Can you use a formula field in a SOQL WHERE clause?
Yes. SOQL accepts a formula field in WHERE like any other field, but Salesforce calculates the value for each record the query considers, and the field has no index by default. On large objects that can mean a full scan.
What is the FORMULA() function in SOQL?
FORMULA() is a Winter '27 beta function that adds or subtracts two fields and compares the result to a literal, for example WHERE FORMULA('Amount - ExpectedRevenue') > 100. It works only in the WHERE clause, requires API version 68.0 and isn't available in production orgs.
Can SOQL compare two fields in the WHERE clause?
Not in a plain field expression: WHERE Amount > ExpectedRevenue is rejected because the right side must be a literal or bind variable. Use FORMULA() in a non-production org, create a formula field that does the comparison, or query a broader set and compare the fields in Apex.
Can a formula field be indexed in Salesforce?
Only if it is deterministic, and only when Salesforce Customer Support adds a custom index. Formulas that use TODAY() or NOW(), or that reference fields on related objects, are non-deterministic and can't be indexed.
Is SOQL FORMULA() available in production?
No. As of Winter '27, FORMULA() is a beta that requires API version 68.0 and isn't available in production orgs. Try it in a sandbox or scratch org, and keep a formula field or an Apex filter in production code until it is GA.
Leave a Comment