Sub topic 10
String.escapeSingleQuotes: a last resort and its limits
This chapter assumes you can read basic Apex and know how a dynamic query is built with Database.query. It also assumes you have seen a SOQL injection (an attacker changing the structure of your query through input) and the bind-variable fix from the earlier chapters. Here you will learn what String.escapeSingleQuotes does, where it works, and where it fails silently.
What the method does
String.escapeSingleQuotes(s) returns a copy of s with a backslash added before each single quote. In a SOQL string literal, \' means "a quote character that belongs to the value". A quote typed by a user therefore cannot end the literal early.
String input = 'O\'Brien\' OR Name != \'';
String safe = String.escapeSingleQuotes(input);
System.debug(safe);
// Prints: O\'Brien\' OR Name != \'Put inside quotes in a query, the escaped text is read as one name that happens to contain quote characters:
String soql = 'SELECT Id, Name FROM Account WHERE Name = \'' + safe + '\'';The method works on text only. It does not parse SOQL and does not know where in the query the value will end up. Its protection is correct in exactly one place: inside a quoted string literal.
Where it is acceptable
Use it only when a bind variable cannot do the job and the value goes inside a single-quoted literal. A bind variable is better for three reasons:
- The value never becomes part of the query text, so there is nothing to escape and nothing to forget.
- It works for every value type, not only strings.
- Reviewers and static analyzers can see at a glance that the query is safe.
Cases where you may still end up using the escape are rare. One is a query fragment assembled by a framework that only accepts a finished string. Another is legacy code you cannot restructure yet. If you can write :name in the query, do that.
A small helper keeps the escape and the surrounding quotes together, so one cannot be added without the other:
public with sharing class SoqlLiteral {
// Returns value as a quoted SOQL string literal, e.g. 'O\'Brien'
public static String quote(String value) {
return '\'' + String.escapeSingleQuotes(value == null ? '' : value) + '\'';
}
}public with sharing class AccountSearchLegacy {
public static List<Account> findByName(String name) {
String soql = 'SELECT Id, Name FROM Account WHERE Name = ' + SoqlLiteral.quote(name);
return Database.query(soql, AccessLevel.USER_MODE);
}
}Note the second argument of Database.query. Escaping protects the structure of the query, not data access. Without AccessLevel.USER_MODE the query runs in system mode, which ignores the running user's field-level security and object permissions.
What it does not protect
The method only handles the single-quote character. Every other way of changing a query passes straight through it.
Unquoted values: numbers, dates, booleans, Ids
An attacker does not need a quote to change a query when the value is not inside a literal. Consider a filter on a number:
public with sharing class EmployeeFilter {
// VULNERABLE: escaping does nothing, because the value is not inside quotes.
public static List<Account> largerThan(String minEmployees) {
String soql = 'SELECT Id, Name FROM Account WHERE NumberOfEmployees > '
+ String.escapeSingleQuotes(minEmployees);
return Database.query(soql);
}
}Calling largerThan('0 OR Name != null') produces:
SELECT Id, Name FROM Account WHERE NumberOfEmployees > 0 OR Name != nullThe input contains no quote, so the escape changes nothing. The condition now matches every account with a name. The fix is to convert the input to the type it represents, then bind it:
public with sharing class EmployeeFilterSafe {
public static List<Account> largerThan(String minEmployees) {
Integer minValue = Integer.valueOf(minEmployees); // throws TypeException on bad input
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE NumberOfEmployees > :minValue',
new Map<String, Object>{ 'minValue' => minValue },
AccessLevel.USER_MODE
);
}
}The same applies to dates, Booleans and Ids. Parse them with Date.valueOf, Boolean.valueOf or Id.valueOf, and bind the typed result.
Field names, object names and sort order
Identifiers are never quoted in SOQL, so escaping cannot protect them. A user-supplied sort field such as Name, (SELECT Id FROM Contacts) or a field the user should not read contains no quote characters. Validate identifiers against an allowlist or a Schema describe lookup, as covered in the chapters on those techniques.
LIKE wildcards
% and _ are not quote characters, so the escape leaves them alone. A user who types % into a LIKE search gets every record. This is not injection in the structural sense, because the query is unchanged. But it can still cause a broad scan or expose more rows than you intended. Decide whether wildcards from users are acceptable. If not, strip or reject them before building the pattern.
Other characters with special meaning
The method does not remove or neutralize newlines, comment-like text, or very long strings. For free text going into a literal, the escape handles the quote and nothing else. Limit the length and the allowed characters on input that has a known shape, such as a postal code or a reference number.
Mistakes that defeat the escape
Even in its one valid use, the method is easy to apply wrongly.
- Escaping the whole query. Calling
String.escapeSingleQuotes(soql)on the finished query also escapes your own quotes, so the query breaks. It does not make attacker input safe either. Escape each value, before it is concatenated. - Escaping, then concatenating a different variable. When a query has several inputs, it is easy to escape one and forget another. A helper like
SoqlLiteral.quotemakes this harder to do by accident. - Escaping and then binding. If you pass an escaped string as a bind variable, the backslashes become part of the value and the search no longer matches what the user typed. Bind the raw value.
- Forgetting the quotes.
'... WHERE Name = ' + escapedhas no literal around the value. The result is either an invalid query or, as in the number example, an injectable one. - Escaping early and storing the result. An escaped string is only correct for one use. If you save it and later use it in a message, a comparison, or a different query, it carries backslashes that were never part of the data. Escape at the moment of building the query.
- Trusting it for second-order input. Data read from the database, a custom setting or a callout response is still untrusted if a user could have written it. Treat it like request input.
Choosing a defense
The decision depends on where the value lands in the query.
The last branch is deliberate. If the value is neither bindable, nor an identifier, nor a quoted string, escaping has nothing to offer, and the safe move is to change the design.
Testing the escape
A test for code that uses the escape should prove two things. The payload is handled as plain text, and unquoted values are not accepted at all.
@IsTest
private class AccountSearchLegacyTest {
@IsTest
static void quotePayloadIsTreatedAsLiteralName() {
insert new Account(Name = 'Acme');
List<Account> result = AccountSearchLegacy.findByName('\' OR Name != \'');
Assert.areEqual(0, result.size(), 'Payload must be treated as a literal name');
}
@IsTest
static void namesWithApostropheStillMatch() {
insert new Account(Name = 'O\'Brien Ltd');
List<Account> result = AccountSearchLegacy.findByName('O\'Brien Ltd');
Assert.areEqual(1, result.size(), 'Legitimate apostrophes must still work');
}
@IsTest
static void numericPayloadIsRejected() {
insert new Account(Name = 'Acme', NumberOfEmployees = 10);
try {
EmployeeFilterSafe.largerThan('0 OR Name != null');
Assert.fail('Expected a TypeException for non-numeric input');
} catch (TypeException e) {
Assert.isTrue(true, 'Non-numeric input is rejected before the query runs');
}
}
}The second test matters as much as the first. A defense that blocks every apostrophe breaks real names, and users then ask for the check to be removed.
Summary of limits
| Input location | Does escapeSingleQuotes help? | Use instead |
|---|---|---|
| String inside quotes in WHERE | Yes, if applied to that value | Bind variable |
| Number, Date, Boolean, Id | No | Parse to a type, then bind |
| Field or object name | No | Allowlist or Schema describe |
| ORDER BY direction | No | Fixed set of `ASC` or `DESC` |
| LIKE wildcards `%` and `_` | No | Decide whether to strip or allow them |
| Sharing, CRUD, FLS | Not related | `AccessLevel.USER_MODE` |
Exercise
A developer writes 'SELECT Id FROM Contact WHERE Age__c > ' + String.escapeSingleQuotes(ageInput), where ageInput comes from a URL parameter. A tester submits 0 OR LastName != null. Does the escape stop the attack, and what is the correct fix?
Show answer
No. The payload has no single quote, and the value is not inside a quoted literal, so the escape changes nothing and the condition matches every contact with a last name. Convert the input with Integer.valueOf(ageInput) (or Decimal.valueOf, depending on the field type), then use a bind variable such as :minAge with Database.queryWithBinds, and run it in AccessLevel.USER_MODE.
Exercise
A search page builds String pattern = '%' + String.escapeSingleQuotes(term) + '%' and passes pattern as a bind variable in a LIKE query. Name two problems with this code.
Show answer
First, the escape is unnecessary and harmful here. A bound value is never read as query text, so the backslash added before an apostrophe becomes part of the search value and O'Brien no longer matches O'Brien. Second, the escape does nothing about % and _ typed by the user, which still act as wildcards, so a term of % matches every record. Remove the escape and decide separately whether to strip or reject wildcard characters.