# What is SOQL Injection, and how do you prevent it using bind variables or String.escapeSingleQuotes()?

**Topic:** Soql · **Difficulty:** Medium · **Asked at:** Salesforce, Deloitte, PwC, Google · **Tags:** soql, security, injection

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-soql-injection-and-how-do-you-prevent-it-using-bind-variables-or-string-escapesinglequotes

## Answer

SOQL injection happens when user input is concatenated into a dynamic query, letting an attacker change its logic (e.g. input `' OR Name != '`).

**Prevention:**
- Use static SOQL with bind variables (`:name`)
- With dynamic SOQL, use `Database.queryWithBinds` or bind variables inside the string
- Sanitize with `String.escapeSingleQuotes()` when you must concatenate
- Validate input against allowed values (whitelist) for field/object names

```apex
String name = String.escapeSingleQuotes(userInput);
String q = 'SELECT Id FROM Account WHERE Name = \'' + name + '\'';
```

---
Source: ForceChallenges · last updated 2026-10-21
