SQL injection is one of the oldest web vulnerabilities and it still shows up in new code. The cause is almost always the same: user input becomes part of the SQL text instead of being passed as data. This guide explains how to fix SQL injection properly, how to find it in your own code before anyone else does, and how to verify the fix. It is written for defenders, so there are no attack strings here, just patterns to recognise and repair.
What SQL injection is, in one paragraph
A database receives a query as text and parses it. If your application builds that text by gluing user input into it, the database cannot tell which parts you wrote and which parts came from the request. Input that contains SQL syntax can then change the meaning of the query: read other rows, change data, or worse. The weakness is catalogued as CWE-89. The fix is to keep code and data apart, so input is never parsed as SQL.
Where it hides in real code
The classic shape is string building, where input becomes part of the SQL text. Do not copy this pattern:
cursor.execute(f"SELECT id, email FROM users WHERE email = '{email}'")
The same mistake appears in other forms:
- String concatenation or template literals in any language.
- ORM escape hatches: raw query methods,
text()fragments, customWHEREsnippets. - Dynamic
ORDER BYcolumns or sort directions taken straight from query parameters. - Stored procedures that build and execute SQL strings internally.
- Reporting and admin screens, which often get less review than the main app.
How to fix SQL injection
The OWASP SQL Injection Prevention Cheat Sheet lists parameterized queries and allow-list input validation as the primary defenses, and strongly discourages manual escaping. In practice, that means four habits.
1. Use parameterized queries everywhere
With parameters, the SQL text is fixed and the values travel separately. The database never parses them as SQL.
Python (DB-API, e.g. psycopg):
cursor.execute("SELECT id, email FROM users WHERE email = %s", (email,))
Node.js (node-postgres):
const res = await pool.query(
"SELECT id, email FROM users WHERE email = $1",
[email]
);
Java (JDBC):
PreparedStatement ps = conn.prepareStatement(
"SELECT id, email FROM users WHERE email = ?");
ps.setString(1, email);
The placeholder style differs by driver (?, %s, $1, :name), but the idea is the same. ORMs use parameters by default for normal queries; the risk returns when you drop down to raw SQL, so apply the same rule there.
2. Allow-list anything that cannot be a parameter
Placeholders can carry values, not table names, column names or keywords like ASC and DESC. When users choose a sort column, map their choice to a value your code owns and reject anything else:
SORT_COLUMNS = {"name": "last_name", "joined": "created_at"}
column = SORT_COLUMNS.get(request_sort, "created_at")
direction = "DESC" if request_dir == "desc" else "ASC"
sql = f"SELECT id, last_name FROM users ORDER BY {column} {direction}"
Here the f-string is safe because every possible value comes from your own dictionary, never from the request.
3. Do not rely on escaping
Hand-written escaping depends on the database, its version and its settings, and one missed call reopens the hole. OWASP's advice is plain: use parameter binding instead of escaping untrusted values yourself.
4. Limit the damage with least privilege
Give each application its own database account with only the rights it needs. A read-only reporting service should not be able to write, and no web app should connect as a database administrator. This does not prevent injection, but it limits what a missed bug can reach.
Input validation (types, lengths, formats) is still worth doing as defense in depth, and a web application firewall can add a layer in front. Neither replaces parameterized queries.
SQL injection detection: finding it before someone else does
Detection works best when you combine several views of the same app. All of these are for code and systems you own or are authorised to test.
Review and search the code
Search for SQL keywords next to string formatting: execute( with +, f"SELECT, .format( near WHERE, template literals with ${ inside queries, and raw query methods in your ORM. Every hit should either use parameters or an allow-list.
Add static analysis to CI
SAST tools such as Semgrep or CodeQL have rules that trace request data into query calls. Run them on pull requests so new cases are caught at review time, not in production.
Run authorised dynamic scans
A DAST scanner such as OWASP ZAP tests the running application and reports parameters that react like injection points. Run it against staging or production only with written permission from the system owner, within the agreed scope and time window.
Watch the signals
Database syntax errors in application logs, unusual query patterns and WAF alerts are useful signals that something is probing a parameter. Treat them as a reason to review that code path.
Verify the fix
A fix is not finished until you have checked it:
- Unit tests with awkward but legitimate input, such as names with apostrophes (O'Brien) or values with quotes and semicolons. With parameters, they are stored and found as plain text.
- Re-run the scan that found the issue, against the same endpoint, and confirm the finding closes.
- Search for siblings. Injection bugs travel in families; the same helper or copy-pasted pattern is often used elsewhere.
- Add a CI rule so the pattern cannot come back quietly.
SQL injection prevention as a routine
The teams that rarely see SQL injection are not the ones with the cleverest filters. They use parameterized queries by default, review raw SQL with care, run static analysis on every change, scan with permission on a schedule, and retest after fixes.
If you manage several applications or clients, CerberusGuard can help with the scanning and retesting part. It runs web and API scans with Nuclei and OWASP ZAP, including OpenAPI-driven API tests, checks a signed scan authorisation before every scan, and offers one-click retests once a fix is deployed. Find issues like this with authorised scans in CerberusGuard.
Originally published at CerberusGuard blog.
Top comments (0)