Sub topic 3
Filtering records with WHERE
The WHERE clause decides which rows a SOQL query returns. Without it, a query returns every record the user can see, up to the limits covered in a later chapter. This chapter covers the filter operators, how to combine conditions, how null values behave, and the mistakes that cause empty results or errors.
It assumes you can run inline SOQL in Apex, as in the previous chapters, and know the standard objects Account, Contact, and Opportunity. Bind variables, date literals, and relationship queries each have their own chapter. This chapter mentions them only where a filter needs one.
Anatomy of a condition
A filter condition has three parts: a field, an operator, and a value.
List<Opportunity> bigOpen = [
SELECT Id, Name, Amount
FROM Opportunity
WHERE Amount >= 50000 AND IsClosed = false
];
System.debug(bigOpen.size() + ' large open opportunities');The field must belong to the object in the FROM clause, or be reached through a relationship. The value must match the field's type:
- Text values go in single quotes:
'Technology'. - Numbers, booleans, and
nullhave no quotes:50000,false,null. - Date and DateTime values also have no quotes, for example
2026-01-31.
Double quotes are not valid string delimiters in SOQL.
Comparison operators
| Operator | Meaning | Notes |
|---|---|---|
| `=` | Equal | Text comparison is case-insensitive on most fields |
| `!=` | Not equal | Also matches rows where the field is null |
| `<`, `<=`, `>`, `>=` | Ordering | Numbers, dates, and text |
| `LIKE` | Pattern match | Text fields only |
| `IN`, `NOT IN` | Match a set of values | Accepts literals, a bound collection, or a subquery |
| `INCLUDES`, `EXCLUDES` | Multi-select picklist match | Only for multi-select picklists |
Two behaviors surprise developers who know SQL.
First, = on text ignores case. WHERE Name = 'acme' finds a record named Acme. A few fields, such as case-sensitive external Ids, are the exception.
Second, != returns rows with a null value. WHERE Industry != 'Technology' includes accounts whose Industry is empty. If you want only accounts that have an industry other than Technology, say so:
List<Account> others = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != 'Technology' AND Industry != null
];Matching patterns with LIKE
LIKE supports two wildcards:
%matches zero or more characters._matches exactly one character.
// Names that start with "Acme"
List<Account> startsWith = [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%'];
// Names that contain "labs"
List<Account> contains = [SELECT Id, Name FROM Account WHERE Name LIKE '%labs%'];
// Exactly one character between "A" and "1", such as "A-1" or "AX1"
List<Account> oneChar = [SELECT Id, Name FROM Account WHERE Name LIKE 'A_1'];A pattern with a leading wildcard, such as '%labs%', cannot use an index. On large objects it forces a scan of many rows. Prefer 'Acme%' when you can.
To match a literal % or _, escape it with a backslash. In Apex source the backslash must itself be escaped, so LIKE '50\\%%' matches text that starts with 50%.
Matching several values with IN
IN is shorthand for several OR conditions on the same field.
List<Account> picked = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry IN ('Technology', 'Energy', 'Finance')
];NOT IN excludes the listed values. A later chapter on bulk-safe patterns shows IN with a collection of Ids, which is the most common use in real code.
IN can also take a subquery. This is called a semi-join. It filters by whether related records exist in another object:
// Accounts that have at least one Contact with an email address
List<Account> reachable = [
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)
];The subquery must select a single field. That field's type must match the field on the left side of IN. The subquery returns no rows to you. It only restricts the outer query.
Multi-select picklists
A multi-select picklist stores its chosen values as one semicolon-separated string. Use INCLUDES and EXCLUDES for these fields, not = or LIKE. The example assumes a custom multi-select picklist Interests__c on Contact.
// Contacts interested in Cloud AND Security, or in Analytics
List<Contact> matches = [
SELECT Id, LastName
FROM Contact
WHERE Interests__c INCLUDES ('Cloud;Security', 'Analytics')
];Inside one string, the semicolon means AND. Between strings, the comma means OR.
Combining conditions
Combine conditions with AND, OR, and NOT. NOT negates the condition after it.
SOQL does not let you mix AND and OR at the same level without parentheses. This query does not compile:
// Compile error: unexpected token 'OR'
// WHERE Industry = 'Technology' AND Name LIKE 'A%' OR Industry = 'Energy'Add parentheses to say what you mean:
List<Account> combined = [
SELECT Id, Name, Industry
FROM Account
WHERE (Industry = 'Technology' AND Name LIKE 'A%')
OR Industry = 'Energy'
];Parentheses also clarify NOT. WHERE NOT (Industry = 'Energy' OR Industry = 'Finance') is easier to read than the equivalent chain of != conditions.
Testing for null
Use = null and != null to test for empty fields. Do not write IS NULL, which is SQL syntax and is not valid in SOQL.
List<Contact> noEmail = [SELECT Id, LastName FROM Contact WHERE Email = null];Boolean fields are never null in the user interface, but you still compare them with = true or = false. A checkbox field compared with = false returns unchecked records.
Fields you cannot filter on
Some field types do not work in a WHERE clause:
- Long text area and rich text area fields cannot be filtered. They have no index and the query fails.
- Encrypted fields support only a few operators, and only for deterministic encryption.
- Fields that your user cannot read cause an error in user mode, covered in the security chapter.
When a filter on one of these fields is necessary, look for another way to narrow the rows. Common options are a formula field, a text field that holds a short copy of the value, or SOSL search.
Escaping values written as literals
When you type a value directly into a query, a single quote inside it must be escaped with a backslash:
List<Contact> obrien = [SELECT Id, LastName FROM Contact WHERE LastName = 'O\'Brien'];Values that come from user input or from variables should not be pasted into the query text. Use a bind variable (:name) instead. The next chapter covers this in detail.
Common errors
- Empty results from a correct-looking query. Check the value's case in picklists with restriction rules, trailing spaces, and whether the record is visible to the running user.
unexpected tokenerrors. Look for mixedAND/ORwithout parentheses, double quotes around strings, orIS NULL.invalid operatororfield not filterable. The field type does not support that operator, or does not support filtering at all.!=returns more rows than expected. Null rows match. AddAND field != null.- Slow queries on large objects. Leading-wildcard
LIKE, negative operators such as!=andNOT IN, and filters on unindexed fields can all force wide scans. The final chapter returns to this.
Exercise
You want accounts whose Industry is either Technology or Energy, and whose Name starts with "G". A teammate writes WHERE Industry = 'Technology' OR Industry = 'Energy' AND Name LIKE 'G%' and the query fails to compile. Write a corrected WHERE clause using IN, and say why the original failed.
Show answer
Use WHERE Industry IN ('Technology', 'Energy') AND Name LIKE 'G%'. The original mixed OR and AND at the same level without parentheses, which SOQL rejects because the intended grouping is ambiguous. The equivalent fix with the original shape is WHERE (Industry = 'Technology' OR Industry = 'Energy') AND Name LIKE 'G%'.
Exercise
A query SELECT Id FROM Account WHERE Industry != 'Technology' returns 120 rows, but you expected only the accounts that have some other industry set. What is the likely cause, and how do you fix the query?
Show answer
In SOQL, != also matches rows where the field is null, so accounts with no Industry are included. Add AND Industry != null to the WHERE clause.