6

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

1

1 Answer 1

7

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.

1
  • @Edelrabe Apex Code and SOQL follow two different sets of rules, so your confusion is understandable. Apex is modeled after Java, while SOQL is modeled after Oracle's SQL syntax (from my limited knowledge of their syntax).
    – sfdcfox
    Mar 21, 2016 at 20:56

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.