Plat-Dev-201 practice question 11 of 30

Assuming that name is a String obtained by a Visualforce page, which two SOQL queries performed are safe from SOQL injection? (Choose two.)

Full set: 204 questions
Answer options
A: apex Copy String query = '%' + name + '%'; List results = [SELECT Id FROM Account WHERE Name LIKE :query]; Correct answer
B: apex Copy String query = 'SELECT Id FROM Account WHERE Name LIKE \'%' + name.noQuotes() + '%\''; List results = Database.query(query);
C: apex Copy String query = 'SELECT Id FROM Account WHERE Name LIKE \'%' + String.escapeSingleQuotes(name) + '%\''; List results = Database.query(query); Correct answer
D: apex Copy String query = 'SELECT Id FROM Account WHERE Name LIKE \'%' + name + '%\''; List results = Database.query(query);
Correct Answer:
A. apex Copy String query = '%' + name + '%'; List results = [SELECT Id FROM Account WHERE Name LIKE :query];; C. apex Copy String query = 'SELECT Id FROM Account WHERE Name LIKE \'%' + String.escapeSingleQuotes(name) + '%\''; List results = Database.query(query);
Explanation

SOQL injection is prevented by not concatenating user-supplied input directly into a dynamic query string. Option A uses a static SOQL query with a bind variable (:query), which is inherently safe as the input is treated as a literal value, not executable code. Option C uses dynamic SOQL but correctly sanitizes the input using String.escapeSingleQuotes(). This method escapes any single quotes in the input string, which is the primary mechanism for SOQL injection attacks, thus making the query safe.

Why Incorrect

B. name.noQuotes() is intended to prevent cross-site scripting (XSS) in Visualforce, not SOQL injection, and does not provide adequate protection.
D. This query directly concatenates the raw name variable into the query string, making it a classic example of a SOQL injection vulnerability.

References

- Salesforce Apex Developer Guide, "SOQL Injection," which explicitly states, "The primary defense against SOQL injection is to avoid using dynamic SOQL queries." and for dynamic cases, "use the escapeSingleQuotes method."

- Salesforce Secure Coding Guide, "SOQL Injection," page 10, which details using bind variables in static queries and String.escapeSingleQuotes() for dynamic queries as the two primary prevention methods.

Scroll to Top