Salesforce SOQL does not support direct field-to-field comparison in a WHERE clause. Attempting to compare two fields of the same object on the right-hand side of a WHERE condition returns a QueryException error.
For example, the following SOQL query attempts to compare the FirstName and LastName fields on the User object directly in the WHERE clause:
List<user> users = [SELECT Id, name FROM User WHERE (FirstName != Lastname)];
This query returns: "System.QueryException: unexpected token: 'Lastname'"
Salesforce does not evaluate the right-hand side of a WHERE condition as a field reference — it expects a literal value. This is a known platform limitation.
This article describes two approaches to filter records based on field-to-field comparisons in Salesforce SOQL.
Since SOQL cannot compare two fields directly in a WHERE clause, create a formula field on the object that evaluates the comparison and returns a text value. You can then filter on the formula field's return value in the SOQL query.
Example — compare FirstName and LastName on the User object:
IF(User.FirstName != User.LastName, 'true', 'false')
This formula returns the text string 'true' when FirstName and LastName are different, and 'false' when they match.
List<User> Users = [SELECT id, name FROM User where NameCompare = 'true'];
As of the Spring '20 release, Salesforce Reports support field-to-field filters natively. This allows you to create a report on the User object and filter by comparing FirstName and LastName directly, without needing a formula field. Note that this feature applies to Reports only — SOQL queries in Apex still require the formula field workaround described above. See: Filter Reports by Field Comparisons with Field-to-Field Filters
Vote and comment on the Salesforce Idea for Field-to-Field filters for SOQL.
000386076

We use three kinds of cookies on our websites: required, functional, and advertising. You can choose whether functional and advertising cookies apply. Click on the different cookie categories to find out more about each category and to change the default settings.
Privacy Statement
Required cookies are necessary for basic website functionality. Some examples include: session cookies needed to transmit the website, authentication cookies, and security cookies.
Functional cookies enhance functions, performance, and services on the website. Some examples include: cookies used to analyze site traffic, cookies used for market research, and cookies used to display advertising that is not directed to a particular individual.
Advertising cookies track activity across websites in order to understand a viewer’s interests, and direct them specific marketing. Some examples include: cookies used for remarketing, or interest-based advertising.