Prevent SQL injection by using parameterized queries (prepared statements) for every database query that includes user input, so the database treats input as data, never as SQL code. For parts of a query that cannot be parameterized, such as table names or sort order, map user choices to a strict allow-list of fixed values. Add least-privilege database accounts, input validation and regular testing as backup layers — never rely on escaping or a firewall alone.
Key takeaways
- Parameterized queries are the primary defense: they separate SQL code from data so injected input can never change the query's logic.
- Escaping user input by hand is error-prone and is not a reliable defense; OWASP strongly discourages relying on it.
- CISA and the FBI call SQL injection an 'unforgivable' vulnerability class and urge vendors to eliminate it with prepared statements.
SQL injection is more than twenty years old, and the fix has been known for almost as long. Yet it still shows up in breach after breach, because developers keep building database queries by gluing user input into SQL strings. The good news: preventing it is mostly a matter of one habit, applied everywhere.
How do you prevent SQL injection attacks?
Use parameterized queries (prepared statements) for every database query that includes user input, so the database treats the input as data and never as SQL code. That single practice stops the entire class of attack at its root.
OWASP's SQL Injection Prevention Cheat Sheet calls parameterized queries the preferred pattern, and CISA and the FBI say the same in their joint Secure by Design alert: software makers should systematically eliminate SQL injection by enforcing parameterized queries across their applications. Everything else in this article — allow-lists, least privilege, validation, firewalls — is a backup layer. Useful, but never a substitute.
What is SQL injection?
SQL injection happens when untrusted data becomes part of a query's SQL syntax and changes the logic of the query. The application builds a query by concatenating user input into a SQL string, and the database cannot tell where the developer's code ends and the attacker's input begins.
The classic example is a login form. The vulnerable code builds a query like this:
String query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
If an attacker enters tom' or '1'='1 as the username, the query becomes ... WHERE username = 'tom' or '1'='1' AND password = '...'. Since '1'='1' is always true, the condition passes and the attacker logs in without the password. The same trick can dump whole tables with UNION SELECT, delete data, or — on some databases — run operating system commands.
SQL injection is listed as CWE-89 and sits under A05:2025 Injection in the OWASP Top 10. It is not a niche bug: it is one of the most dangerous and most persistent weakness classes in software.
What are the main types of SQL injection?
All SQL injection works the same way — input changing query logic — but attackers use different techniques depending on what the application reveals. Knowing the types helps you test for them and recognize them in logs.
| Type | How it works | What the attacker gets |
|---|---|---|
| In-band (UNION-based) | Injected query results appear in the page response | Data from other tables, shown directly |
| Error-based | Database error messages leak structure | Table and column names, query details |
| Blind (boolean/time-based) | No data returned; attacker asks yes/no questions | Data extracted one bit at a time, slowly |
| Out-of-band | Results sent to an attacker-controlled server | Data exfiltration when no output channel exists |
| Second-order | Malicious input is stored, then used in a later query | Delayed exploitation that scanners often miss |
Blind injection is the one teams underestimate. The application shows nothing unusual — the page just loads slightly slower, or a "yes" answer changes one word on the page. An attacker can still extract an entire database that way, one question at a time. It is slow, but automation makes it practical.
Second-order injection is the one code reviews miss. The payload is stored safely — in a username, a comment, a profile field — and only becomes dangerous later, when another part of the application uses that stored value in a query without parameterizing it. Parameterize every query, including the ones that read stored data, not just the ones that take fresh input.
Defense 1: Use parameterized queries everywhere
A parameterized query defines the SQL structure separately from its data values, then binds the values through the database API. The database compiles the query first, with placeholders, and the input can only ever fill a value slot — it cannot become SQL syntax.
Here is the safe version of the login query in Java, from OWASP's examples:
String query = "SELECT account_balance FROM user_data WHERE user_name = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, customerName);
ResultSet results = statement.executeQuery();
The same pattern exists in every language. In Python, pass values as a second argument instead of formatting them into the string:
# Wrong: f-string puts input inside the query
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
# Right: the driver binds the value separately
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
In PHP, use PDO with bound parameters. In .NET, use SqlCommand with SqlParameter. In Node.js, use your driver's placeholder syntax — never template literals. OWASP's Query Parameterization Cheat Sheet has working examples for Java, .NET, PHP, Ruby, Python, Perl, ColdFusion and Rust.
One warning from OWASP: parameterize on the server side. Some client-side libraries build queries with string concatenation before sending raw SQL to the server — that is not parameterization, and it is not safe.
Defense 2: Stored procedures and ORMs — use them correctly
Stored procedures are often listed as a defense, but they only help if they are written safely. A procedure that builds SQL by concatenating its arguments is just as vulnerable as application code that does the same thing. Use static SQL with parameters inside the procedure, or bind values in any dynamic SQL it constructs.
Modern ORMs remove most of the risk by default. The Django ORM and SQLAlchemy parameterize everything for the bulk of data access, which is a big reason injection has dropped down the OWASP list. The catch is the escape hatch: the moment you reach for raw SQL, a query builder's raw method, or string formatting to build a filter, you are responsible for parameterizing again. Review every raw-SQL call in your codebase as if it were hand-written SQL, because it is.
The same rule applies to reporting tools, admin panels and data-export features — the places where developers most often write "just this once" raw SQL. Those are also the places with the broadest database access.
Defense 3: Allow-lists for table names, columns and sort order
Some parts of a query cannot be parameterized: table names, column names and sort direction (ASC / DESC) are structure, not data, so placeholders do not work for them. The fix is to never take these values from the user directly.
Instead, map user choices to a strict allow-list of fixed, application-owned values. If the user picks a sort column, accept only the exact column names your code defines; anything else is rejected or replaced with a default. If the user picks a sort direction, accept only ASC or DESC. This is the approach OWASP recommends, and it is simple to implement: a small dictionary lookup instead of string interpolation.
Do not try to sanitize these values with a block-list of "dangerous" words. Block-lists are incomplete by nature, and attackers are creative about bypasses — encoded characters, case variations and database-specific syntax. An allow-list fails closed: anything not explicitly permitted is refused.
Defense 4: Secondary layers — validation, least privilege and error handling
Secondary defenses do not prevent SQL injection on their own, but they limit the damage when a flaw slips through. Treat them as depth, not as the fix.
- Least privilege. The application's database account should have only the permissions it needs: read and write on its own tables, nothing else. It should not be able to drop tables, create users, read system tables or run operating-system commands. If an injection flaw is found, a least-privilege account turns a full database compromise into a limited one.
- Input validation. Validate input as a secondary defense: reject values that cannot be legitimate for a field, such as non-numeric input in a numeric field. Validation helps, but it cannot be the primary defense, because attackers can craft input that passes it.
- Safe error handling. Never return raw database errors to users. Error messages leak table names, column names and query structure — exactly what an attacker needs for error-based injection. Log the full error server-side and show the user a generic message.
- Web application firewall. A WAF can block many known injection patterns and buys time while code is fixed. It is not a fix: attackers regularly find bypasses, and a WAF cannot protect queries built unsafely.
- Keep the database patched. Database engines and drivers get security updates too, and some injection techniques depend on known engine behavior. Patching is basic hygiene, not a defense in itself.
Manual escaping — adding backslashes or doubling quotes by hand — is error-prone and is strongly discouraged by OWASP as a primary defense. Every database has its own escaping rules, and getting one edge case wrong reopens the flaw. If you are writing escaping code yourself, you are almost certainly doing something that a parameterized query would do better.
How do you test for SQL injection?
Testing has three parts, and you need all of them. First, review code: search for string concatenation in queries, raw SQL calls, and dynamic SQL in stored procedures. A simple search for + next to SQL strings, or for execute( with formatted strings, finds most of the risk quickly.
Second, run dynamic testing against a staging environment: application security scanners (DAST) and targeted tools such as sqlmap probe inputs with known payloads and report which ones change query behavior. Only run these against systems you own or are authorized to test — probing a live system without permission is unauthorized access, as our guide to whether ethical hacking is legal explains.
Third, test the fix, not just the finding. After parameterizing a query, re-run the same payloads and confirm they are treated as literal data. Add regression tests so a future developer cannot quietly reintroduce concatenation. The best time to catch SQL injection is in code review, before the query ever reaches production.
Real cases: MOVEit and TalkTalk
In May 2023, the Clop ransomware group exploited a SQL injection zero-day in Progress MOVEit Transfer, a managed file transfer application used by thousands of organizations. The flaw let attackers steal data from MOVEit servers worldwide, and the breach count ran into the thousands of affected organizations. CISA and the FBI issued their Secure by Design alert in response, calling SQL injection an "unforgivable" vulnerability — one the industry has known how to prevent since at least 2007.
An earlier case shows the same pattern at smaller scale. In 2015, the UK telecom TalkTalk was breached through a SQL injection flaw; the attackers accessed personal data of about 157,000 customers, and the company was later fined £400,000 by the UK's Information Commissioner's Office. The entry point was a legacy web page that had not been properly tested.
Both cases share the same lesson: the vulnerability was not exotic, the fix was not new, and the damage was entirely preventable. SQL injection survives because old code, acquired code and rushed features keep reintroducing it.
Common mistakes that keep SQL injection alive
The same five mistakes appear in almost every SQL injection incident. Check your codebase for each one.
- Concatenating input into queries — the root cause. Any
+, f-string or template literal building SQL is a bug waiting for an attacker. - Parameterizing only some queries — admin panels, reporting tools and search features get skipped because they feel internal. Attackers find them anyway.
- Trusting stored data — values already in the database are treated as safe and concatenated into later queries. That is second-order injection.
- Relying on a WAF as the fix — the firewall blocks the payloads it knows, and the attacker tries the ones it does not.
- Returning database errors to users — error messages hand attackers the schema on a plate.
If your team does one thing after reading this article, make it a code-review rule: no query is merged unless its inputs are bound as parameters or mapped through an allow-list. You can check the surrounding security of your own site in seconds with our free security headers checker.
While you are at it, confirm your site's TLS setup with our SSL checker.
The bottom line
SQL injection is a solved problem with an unsolved adoption problem. Parameterized queries stop it completely, for every language and every database. Allow-lists handle the structural parts that parameters cannot reach. Least privilege, validation and a WAF limit the damage if a flaw slips through.
Start with a search of your own codebase for concatenated queries — that is where the risk lives. Fix those, add a code-review rule so they cannot come back, and test the fix with the same payloads an attacker would use. The vulnerability is older than most of the developers who still write it; the fix is older still.
Frequently asked questions
What is the best way to prevent SQL injection?
Use parameterized queries with prepared statements for every query that includes user input. This is the primary defense recommended by OWASP and by CISA and the FBI, because it separates the SQL code from the data so injected input cannot change the query.
Does input validation prevent SQL injection?
Not on its own. Input validation is a useful secondary defense, but attackers can craft input that passes validation. It should back up parameterized queries, never replace them.
Can a web application firewall stop SQL injection?
A WAF can block many known attack patterns, but it is a backup layer, not a fix. Attackers regularly find bypasses, and a WAF cannot protect queries that are built unsafely. Fix the code first.
Do stored procedures prevent SQL injection?
Not automatically. A stored procedure that builds SQL by concatenating its arguments is still vulnerable. Use static SQL with parameters inside the procedure, or bind values in any dynamic SQL it constructs.
Do ORMs prevent SQL injection?
Mostly. ORMs such as the Django ORM and SQLAlchemy parameterize queries by default, which removes the risk for normal use. The risk returns the moment you use raw SQL, string formatting or a query-builder escape hatch — parameterize those too.
What is an example of SQL injection?
Entering tom' or '1'='1 in a login field can turn SELECT * FROM users WHERE username = 'tom' AND password = '...' into a query where '1'='1 is always true, letting the attacker log in without the password. With parameterized queries, the whole string is treated as a literal username.
How do you test for SQL injection?
Review code for string concatenation in queries, run dynamic scanners (DAST) against a test environment, and use tools such as sqlmap only against systems you own or are authorized to test. Fix findings by parameterizing the query, not by blocking the test input.
Is SQL injection still a problem in 2026?
Yes. OWASP lists injection as A05 in the 2025 Top 10, and CISA and the FBI issued a Secure by Design alert after a SQL injection flaw in MOVEit Transfer was exploited against thousands of organizations in 2023.
Sources
The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.
Checked against the OWASP SQL Injection Prevention and Query Parameterization cheat sheets and the joint CISA/FBI Secure by Design alert.
How we write and fact-check →