SOQL does not currently support a direct field for comparing fields in WHERE clauses. From Field to compare fields in a WHERE clause in SOQL
Comparing fields with fields in a WHERE clause for SOQL
Article Code: 000187460
Description
I want to execute the query by comparing two fields of the same object in the WHERE clause, but I cannot use the field on the right side of the condition in the WHERE clause:
List<user> users = [SELECT Id,name FROM User WHERE (FirstName != Lastname)];
The above query returns: "System.QueryException: unexpected token: 'Lastname'"
Resolution
Salesforce does not allow a direct field to compare fields in a SOQL query.
To do this, you can create a formula field that will compare the fields and return a value (for example, true or false) that you can use in WHERE.
So, for the above query, you can create a formula field for the user object with the return type Text, for example. NameCompare, with the formula IF (User.FirstName! = User.LastName, 'true', 'false')
Now our request will look like this:
List<User> Users = [SELECT id, name FROM User where NameCompare= 'true'];
The following idea was posted on the ideaexchange portal to allow comparison of fields between fields in SOQL:
https://success.salesforce.com/ideaView?id=08730000000BrHAAA0
You can create a formula field of type checkbox to return a boolean:
Approved_Date__c > Last_Upload_Date__c
Then rewrite the query with the WHERE clause, for example:
SELECT Id FROM Price_Agreement_Item__c WHERE Approved_Date_Greater_Than_Last_Upload_Date__c = true
Be careful how many lines are required to scan. It cannot use the index, so it will result in a full table scan. If the number of lines becomes too large, you may receive other errors.
By the way, Salesforce Stack Exchange is a great place to ask specific Salesforce questions. This answer refers to a question from there answered by Jesse Altman with comments by Keith C and sfdcfox.