The SOQL IN operator and relationship queries are essential tools for retrieving related records from multiple Salesforce objects in a single query. This guide covers both the IN operator syntax and relationship patterns that every Salesforce developer needs to master.
What is the SOQL IN Operator?
The SOQL IN operator filters records by matching field values against a list of specified values or a subquery result. It’s more efficient than multiple OR conditions when filtering on multiple values.
Basic IN Operator Syntax
// Basic IN with literal values
SELECT Id, Name FROM Account WHERE Industry IN ('Technology', 'Healthcare', 'Finance')
// IN with subquery
SELECT Id, Name FROM Account WHERE Id IN (
SELECT AccountId FROM Contact WHERE CreatedDate = LAST_N_DAYS:30
)
SOQL IN vs OR Operator
The IN operator in SOQL is more readable and efficient than multiple OR conditions:
| Using IN Operator | Using OR Operator |
|---|---|
WHERE Industry IN ('Tech', 'Finance') |
WHERE Industry = 'Tech' OR Industry = 'Finance' |
| More concise and readable | Verbose for multiple values |
| Better query plan optimization | Less efficient for many values |
SOQL Relationship Query Patterns
SOQL relationships between objects allow you to query records from one or more objects in a single statement. There are three main relationship patterns:
- Parent-to-Child relationships (1:n)
- Child-to-Parent relationships (n:1)
- Many-to-one relationships with filtering
Parent-to-Child Relationship Queries
When querying from parent to child, use a subquery within the main SELECT statement. For standard objects, the relationship name equals the plural of the child object name.
// Standard objects: Account to Contacts
SELECT Name, (SELECT LastName FROM Contacts) FROM Account
// With IN operator filtering
SELECT Name, (SELECT LastName FROM Contacts WHERE CreatedDate IN (LAST_N_DAYS:30)) FROM Account
WHERE Industry IN ('Technology', 'Healthcare')
