[SalesForce] Unexpected token OR

What's wrong with this SOQL:

SELECT Id, Email, Name
FROM Contact
WHERE AccountId = '0014000000p6XlS' AND LastName LIKE 'test' OR email LIKE 'test'

I have the following error:

MALFORMED_QUERY: '0014000000p6XlS' AND LastName LIKE 'test' OR email
LIKE 'test' ERROR at Row:3:Column:61 unexpected token: OR

Best Answer

You can't mix AND and OR without using parentheses (()). This avoids ambiguity by forcing you to specify the proper conditions. As written, the database would have to make a choice between:

// Query 1
SELECT Id, Email, Name
FROM Contact
WHERE (AccountId = '0014000000p6XlS' AND LastName LIKE 'test') OR email LIKE 'test'

// Query 2
SELECT Id, Email, Name
FROM Contact
WHERE AccountId = '0014000000p6XlS' AND (LastName LIKE 'test' OR email LIKE 'test')

Instead, it simply returns an error and forces you to make the correct choice.

This behavior is noted in the documentation:

You can use parentheses to define the order in which fieldExpressions are evaluated. ... Client applications must specify parentheses when nesting operators. However, multiple operators of the same type do not need to be nested.

Related Topic