← All articles
Salesforce · SOQL · Security · Quick Reads

SOQL LIKE: Wildcards, Special Characters, and Safe Escaping

SOQL LIKE looks simple until the search value contains wildcard or quote characters.

Starts With

SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'

% matches zero or more characters.

Contains

SELECT Id, Name
FROM Account
WHERE Name LIKE '%Cloud%'

Single-Character Wildcard

_ matches one character:

SELECT Id, Name
FROM Account
WHERE Name LIKE 'A_me'

This can match values where exactly one character appears between A and me.

Searching for Literal % or _

When % or _ is data rather than a wildcard, escape it with a backslash in the SOQL pattern. Remember that the host language may require its own escaping too.

Conceptually:

WHERE Name LIKE 'Save 20\%'

The exact string you write in Apex, JavaScript, Java, MuleSoft, or an API request can require another escaping layer. Always distinguish SOQL escaping from programming-language/transport escaping.

Apostrophes and Dynamic SOQL

A name such as O'Reilly can break a dynamically concatenated query if handled incorrectly. More importantly, raw concatenation of user input creates a SOQL injection risk.

Prefer Apex bind variables:

String searchText = '%' + userInput + '%';
List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Name LIKE :searchText
];

If dynamic SOQL is genuinely required, use Salesforce-supported binding mechanisms where possible. For legacy string construction, String.escapeSingleQuotes() addresses quote escaping, but secure query construction should not depend on ad hoc concatenation.

Multiple LIKE Conditions

SELECT Id, Name
FROM Account
WHERE Name LIKE 'Acme%'
   OR Name LIKE 'Global%'

For many search terms, consider whether SOSL is a better fit. SOQL is best when you know the object and fields you are filtering; SOSL is designed for text search across searchable fields and potentially multiple objects.

Performance Note

A leading wildcard such as %Cloud or %Cloud% is less selective than a prefix pattern such as Cloud%. On large data volumes, broad text filters can become expensive. Query only what the use case needs and test realistic data volumes.

References

CONTINUE READING

Explore closely related architecture, integration and implementation topics.