In short
Prevent SQL injection by using parameterised queries, or prepared statements, for all user input, so that the database treats input as data and never as code. Use an ORM's safe query builder, but watch its raw query features. Column names and sort orders can't be parameters, so check them against an allow-list. Then add least-privilege database accounts and automated scanning as further protection.
What it is
SQL injection happens when user input changes the meaning of a database query. Here's a classic mistake:
// VULNERABLE: input is joined into the SQL
const sql = "SELECT * FROM users WHERE email = '" + email + "'";
await db.query(sql);
If someone submits ' OR '1'='1 as their email, the query becomes:
SELECT * FROM users WHERE email = '' OR '1'='1'
That returns every user. A more determined attacker might read other tables or change data, or even go further, depending on the database's permissions. It's still in the OWASP Top Ten, under injection.
It's worth checking generated code for this. AI tools have been reported to concatenate input into queries at times, and SQL injection is one of the categories in Veracode's tests. See is AI-generated code safe to ship?
The fix: parameterised queries
Send the SQL and the values separately. The database compiles the query's structure first, so the input can only ever be treated as data.
// the input changed the query
$1 = ' OR '1'='1
// just an odd email address
Node.js with Postgres:
const result = await db.query(
"SELECT * FROM users WHERE email = $1",
[email]
);
PHP with PDO:
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
Python with psycopg:
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
Note that the Python example passes the value separately, and isn't formatting a string. Using Python's % operator or an f-string in the SQL would bring the vulnerability back, even though it looks almost identical.
Where ORMs don't save you
ORMs use parameters by default, which prevents most injection. Risks appear when you step outside their safe paths:
- Raw query functions. Many ORMs have one, with safe and unsafe forms. Learn the difference.
- String interpolation in query helpers. For example, Prisma's
$queryRawwith a tagged template is parameterised, while$queryRawUnsafewith a built-up string isn't. - Dynamic filters built from user input, such as letting a client send arbitrary field names.
- JSON or search operators that accept untrusted structures.
- Old versions with known issues. Keep dependencies up to date.
Search your codebase for raw SQL functions and string concatenation near SQL keywords. It's a quick and very effective check.
The cases parameters can't handle
Parameters work for values, but not for identifiers such as table names, column names or keywords like ASC. So a dynamic sort needs a different approach:
// Safe: map input to a fixed list
const allowedSort = { name: "name", created: "created_at" };
const column = allowedSort[req.query.sort] ?? "created_at";
const direction = req.query.dir === "desc" ? "DESC" : "ASC";
const sql = "SELECT id, name FROM users ORDER BY " + column + " " + direction + " LIMIT $1";
await db.query(sql, [limit]);
Note that the values coming from the user never reach the SQL. They only select from your fixed list. This is the right approach for tables, columns and sort orders. Avoid trying to “clean” such input by removing characters, as filters like that are often bypassed.
LIKE searches also deserve care: parameterise them, and escape % and _ if you don't want users to include wildcards.
Stored procedures and second-order injection
Stored procedures help only if they don't build dynamic SQL inside themselves. A procedure that concatenates its input is as vulnerable as application code.
Second-order injection occurs when data is stored safely, but then used unsafely later. A malicious username can sit harmlessly in your table, until a report query concatenates it. So parameterise every query, including those using data from your own database. Treat nothing as trusted, because of where it came from.
Defence in depth
Parameterised queries are the main control. These limit the damage if something slips through:
- Least privilege. Your application's database user shouldn't be able to drop tables, or read things it doesn't need. Use separate accounts for migrations and for the app.
- Row Level Security. Even with a bad query, policies can limit what's returned, when they're set up properly.
- Don't expose raw errors. Detailed database errors help attackers. Log them privately, and show users a plain message.
- Validate input. Check type, length and format on the server. Note that validation helps, but it isn't a replacement for parameters. A valid name can still contain an apostrophe.
- A web application firewall can block common attacks, as an extra layer. It shouldn't be your only protection.
- Encrypt or hash sensitive data, and store passwords properly, so that any leak does less harm.
How to test for it
- Search the code. Look for string concatenation or interpolation in queries, and for raw query functions.
- Use static analysis. Tools such as Semgrep and CodeQL can flag many of these patterns in CI.
- Test the app. Try a single quote in each input, as well as in URL parameters, headers and JSON fields. A 500 error or odd behaviour is a warning sign.
- Run a dynamic scanner, such as OWASP ZAP, or sqlmap, against a staging environment that you own. Never test systems that you don't have permission to test.
- Add regression tests with awkward inputs, including names with apostrophes such as O'Brien, which also catch ordinary bugs.
- Commission a penetration test, for systems with sensitive data.
If you find one in production
Fix it first. Then check your logs for signs of exploitation, such as unusual queries, error spikes or strange parameters. Work out what data could've been reached, rotate any exposed credentials, and consider whether you have to notify anyone. See what GDPR means in practice. Search the whole codebase for the same pattern too, since these bugs tend to appear in groups.
Want a security review of your application? Book a call. You can also see how to prevent XSS for the browser-side equivalent.
Common questions
What is the best way to prevent SQL injection?
Use parameterised queries, also called prepared statements, for all values. The database then treats user input purely as data. Then add least-privilege database accounts and automated testing as extra protection. Avoid building SQL by joining strings.
Do ORMs prevent SQL injection?
Mostly, when you use their normal query builders, as they parameterise values. Risks appear with raw query functions, string interpolation and dynamic field names. Review those places specifically, and keep your ORM updated to avoid known vulnerabilities.
Is input validation enough to stop SQL injection?
No. Validation is a useful extra layer, but legitimate input, such as a name with an apostrophe, may contain characters that matter to SQL. Parameterised queries are the actual fix. Validate as well, but never instead.
How do I safely sort by a user-selected column?
Column names can't be parameters, so map the user's input to a fixed list of allowed columns and directions in your code. The user's value only selects an option from your list, and never gets inserted into the SQL.