What Is SQL Injection? How It Works and How to Prevent It
SQL injection happens when user input is concatenated into a SQL statement, so the database parses part of that input as code rather than data. The fix is not to filter the input, it is to stop building the statement from strings: use a parameterised query, where the SQL and the values travel separately and the database never confuses one for the other.
Topic: Web & API Security in Cybersecurity & Ethical Hacking · Tutorial
Quick answer: SQL injection happens when user input is concatenated into a SQL statement, so the database parses part of that input as code rather than data. The fix is not to filter the input, it is to stop building the statement from strings: use a parameterised query, where the SQL and the values travel separately and the database never confuses one for the other. OWASP ranks it within A03:2021 Injection, mapped to CWE-89, and reports that 94% of applications it assessed were tested for some form of injection.
Key takeaways
- The bug is string concatenation, not "bad input". Input is only dangerous because the query was built by gluing text together.
- Parameterised queries fix it properly. The database receives the statement and the values separately and never reparses the values.
- Escaping and input validation are mitigations, not fixes. OWASP calls validation "not a complete defense".
- Parameters cannot carry table or column names. That case needs an allowlist, and it is where real applications still break.
- Stored procedures are not automatically safe: OWASP notes they "can still introduce SQL injection" if they concatenate internally.
Topics covered in this guide: what SQL injection is, how it works with a worked example, the main types, what an attacker can achieve, the correct fix in three languages, why validation and escaping are not enough, the identifier problem, defence in depth, how to test for it legally, and why it still appears after decades.
Table of Contents
- What Is SQL Injection?
- How Does It Actually Work?
- What Are the Main Types?
- What Can an Attacker Actually Achieve?
- How Do You Actually Prevent It?
- Why Is Input Validation Not Enough?
- What About Table and Column Names?
- What Other Defences Help in Depth?
- How Is SQL Injection Tested For Legally?
- Why Does It Still Appear After Decades?
- References
What Is SQL Injection?
SQL injection is a flaw where data supplied by a user ends up being interpreted by the database as part of the SQL statement rather than as a value inside it. The attacker does not break the database; they write a small part of the query the developer intended to write themselves.
OWASP places it in A03:2021 Injection, a category that maps to 33 CWEs including "CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')". The category's own summary notes that "Injection slides down to the third position", having previously been first. That decline is worth reading correctly: it reflects better framework defaults rather than the problem being solved.
The figures OWASP publishes for the category are a maximum incidence rate of 19%, an average of 3%, and 274,228 total occurrences, with "94% of the applications were tested for some form of injection".
How Does It Actually Work?
Start with the bug in its usual form. A login lookup, written by concatenation:
# VULNERABLE. Do not use.
query = "SELECT id, name FROM users WHERE email = '" + email + "'"
cursor.execute(query)
With a normal value the statement is what the developer expected:
SELECT id, name FROM users WHERE email = '[email protected]'
Now supply ' OR '1'='1 as the email. The string that reaches the database is:
SELECT id, name FROM users WHERE email = '' OR '1'='1'
The quote the attacker supplied closed the literal the developer opened. Everything after it is parsed as SQL, so the condition is now always true and the query returns every row.
Notice what went wrong. The database behaved correctly throughout: it was handed a statement and it parsed it. The defect happened earlier, when the application built one string containing both instruction and data, and in doing so destroyed the distinction between them. That is why the fix is structural rather than a matter of filtering.
What Are the Main Types?
| Type | How the attacker learns the result | Typical sign |
|---|---|---|
| In-band, error-based | The database error is shown in the response | SQL syntax errors visible to the user |
| In-band, union-based | Extra rows appended to the legitimate result | Unexpected data in a normal listing |
| Blind, boolean-based | The page differs between true and false conditions | Subtle content changes, no error |
| Blind, time-based | The response is delayed when a condition is true | Consistent multi-second responses |
| Out-of-band | The database makes a DNS or HTTP request | Nothing visible in the response at all |
The important point for defenders is that the last three leak no information through the page, so "we would see the errors" is not a detection strategy. Suppressing database errors in production is good practice and does not remove the vulnerability; it only removes the easiest version of it.
What Can an Attacker Actually Achieve?
- Read any data the application's database user can read, which in most applications is everything.
- Bypass authentication, as in the example above.
- Modify or delete data, where the account has write permission.
- Read files or run commands, on some database platforms and configurations.
- Move further in, because the database is usually trusted by other systems.
The scope is set by the permissions of the account the application connects with, which is why least privilege matters so much here. The same reasoning applies to authorisation flaws generally, which our guide to broken access control covers. An application that connects as a database owner turns a read flaw into a total compromise.
How Do You Actually Prevent It?
Stop building statements from strings. OWASP's first recommendation is a safe API that "provides a parameterized interface, or migrates to Object Relational Mapping Tools (ORMs)".
With a parameterised query, the statement and the values are sent separately. The database parses the statement once, with placeholders where the values go, and then binds the values in. A value can never be reparsed as SQL because parsing already finished.
Python, using placeholders rather than formatting:
# Correct. The driver sends SQL and parameters separately.
cursor.execute(
"SELECT id, name FROM users WHERE email = %s AND active = %s",
(email, True),
)
PHP with PDO:
$stmt = $pdo->prepare(
'SELECT id, name FROM users WHERE email = :email AND active = :active'
);
$stmt->execute([':email' => $email, ':active' => 1]);
Java with JDBC:
String sql = "SELECT id, name FROM users WHERE email = ? AND active = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, email);
ps.setBoolean(2, true);
ResultSet rs = ps.executeQuery();
}
One warning that catches people who think they have done this correctly. A prepared statement built by concatenation is still vulnerable, because the concatenation happened before the database saw anything:
// STILL VULNERABLE. The string was built before preparing it.
String sql = "SELECT id FROM users WHERE email = '" + email + "'";
PreparedStatement ps = conn.prepareStatement(sql);
The protection comes from the placeholder, not from the word "prepared".
OWASP also notes that stored procedures are not automatically safe: "Even when parameterized, stored procedures can still introduce SQL injection" where the procedure concatenates query text and data internally.
Why Is Input Validation Not Enough?
Because it is trying to answer a question that should not have been asked. Once you are deciding which characters are dangerous, you have already accepted a design where the input could be interpreted as code.
OWASP's position is that positive server-side input validation is recommended and is "not a complete defense". Three reasons it fails as a primary control:
- Legitimate data contains the characters you want to block. Names with apostrophes are the standard example, and blocking them is a bug rather than a control.
- Encodings and database quirks defeat blocklists. There is always another representation.
- It has to be applied everywhere, forever. Parameterisation protects the one query it is used in; validation has to be right at every entry point.
Escaping has the same status. OWASP recommends it only for queries that cannot be parameterised, and specifically to "escape special characters using the specific escape syntax for that interpreter". It is a fallback, and getting it right requires knowing the exact interpreter.
Validate input because it improves data quality and catches mistakes. Do not rely on it to stop injection.
What About Table and Column Names?
This is the real-world case parameterisation does not solve, and OWASP states the limit plainly: identifiers such as table and column names cannot be escaped.
It arises whenever a user controls sorting or filtering:
# VULNERABLE. A placeholder cannot carry a column name.
cursor.execute("SELECT * FROM orders ORDER BY " + sort_column)
The only safe approach is an allowlist, mapping user input to values you wrote yourself:
SORT_COLUMNS = {
"date": "created_at",
"amount": "total_amount",
"status": "status",
}
column = SORT_COLUMNS.get(sort_key)
if column is None:
raise ValueError("unknown sort key")
cursor.execute("SELECT * FROM orders ORDER BY " + column + " DESC")
The concatenation in the last line is safe because column can only ever be one of three strings that appear in your source code. The user chooses between options; they never supply the value.
What Other Defences Help in Depth?
None of these replaces parameterisation. They reduce what a missed instance costs.
- Least privilege. The application account should not own the schema, and read-only workloads should use a read-only account.
- Suppress database errors in responses, and log them server-side instead.
- Static analysis in the pipeline, which finds concatenated queries reliably because the pattern is mechanical.
- A web application firewall, as a delaying measure for known payload shapes, never as a fix.
- Code review that looks for string building, which is faster than looking for vulnerabilities.
- Monitoring for the blind variants, particularly consistent multi-second query times.
How Is SQL Injection Tested For Legally?
Only against systems you own or deliberately vulnerable targets published for training. Testing anything else, including your employer's site without written authorisation, is unauthorised access under the Information Technology Act. Our guide to cyber security projects for beginners covers how to build a lab for this properly.
Within that scope, testing combines manual probing and tooling. The manual part is a mindset rather than a payload list: find every place input reaches a query, then check whether the application distinguishes a value from syntax.
A first manual check, on your own application:
# does a single quote change the behaviour?
curl -s "http://localhost:8080/search?q=test%27" | head -20
# does a boolean condition change the result set?
curl -s "http://localhost:8080/search?q=test%27%20OR%20%271%27=%271" | wc -c
# does a time-based condition delay the response?
time curl -s "http://localhost:8080/search?q=test%27%20AND%20SLEEP(5)--%20" > /dev/null
If the third command takes five seconds longer than the first, the input reached the query engine and the application is vulnerable even though nothing appeared on the page. Our guide to web application security tools covers the tooling side.
Why Does It Still Appear After Decades?
Four reasons, and none of them is that developers do not know about it.
- Concatenation is the obvious way to build a string. The vulnerable version is what you write if you are not thinking about SQL injection at that moment.
- Old code outlives the advice. Most injection found today is in code written years ago by someone no longer there.
- Frameworks protect the common path and not the edges. An ORM protects the queries it generates, and the raw query somebody added for a report is where the flaw sits.
- The identifier case has no framework answer, so sorting and filtering features keep reproducing it.
The practical takeaway for a developer is narrow and worth more than a payload list: if a query is being built by joining strings, stop and use a placeholder, and if the thing being joined is a table or column name, use an allowlist. Those two rules close nearly every real instance.
Talk to a WebAsha training advisor about batches, syllabus and current fees.
References
Related reading
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0