01 / 20

SQL Injection
& Mitigations

Learn how attackers exploit unsanitized database queries and how to defend against them with parameterized queries and secure coding practices.

Cyber Security

What is SQL?

Structured Query Language (SQL) is the standard language for interacting with relational databases. Web applications use SQL to read, write, update, and delete data stored in tables.

SELECT username, email FROM users WHERE id = 42;

What is SQL Injection?

SQL Injection (SQLi) is an attack where a malicious user inserts harmful SQL code into an input field. If the application builds queries by concatenating user input directly, the database executes the attacker's code as if it were legitimate.

✕ The Problem
User input is treated as executable code instead of plain data.
★ The Impact
Attackers can steal, modify, or destroy entire databases.

Why Should You Care?

Data Breaches
Millions of records (passwords, credit cards) stolen from major companies.
Financial Loss
Average data breach costs $4.45 million (IBM, 2023).
Legal Liability
Organizations face lawsuits and regulatory fines for failing to protect data.

How SQL Injection Works

User Input Web App Builds Query Database Executes SQL Danger: Malicious input becomes part of the query ' OR '1'='1' -- injected into WHERE clause Normal Flow

The Vulnerable Query

✕ Unsafe: String Concatenation
// Server-side code (pseudocode) query = "SELECT * FROM users WHERE username = '" + userInput + "' AND password = '" + passInput + "'";

If a user types ' OR '1'='1' -- as the username, the query becomes:

SELECT * FROM users WHERE username = '' OR '1'='1' -- ' AND password = '...'

Types of SQL Injection

In-Band (Classic)
The attacker uses the same channel to inject and retrieve data. Most common type: results appear directly on the page.
Blind SQLi
No visible error or data returned. The attacker infers information from true/false responses or time delays.
Out-of-Band
Data is exfiltrated via a different channel (e.g., DNS or HTTP requests to an attacker-controlled server).

Data vs. Code

The fundamental flaw behind SQL injection is a confusion of boundaries. The database engine cannot distinguish between what the developer intended as structure and what the user supplied as content.

Safe (Data) Dangerous (Code)
User types alice ' OR '1'='1
DB interprets as A string value SQL logic (always true)
Result Returns alice's record Returns all records
Intent Legitimate lookup Authentication bypass

The Fix: Parameterized Queries

A parameterized query (also called a prepared statement) separates the SQL structure from the data. The database engine compiles the query template first, then binds user input strictly as data values.

✓ Safe: Parameterized Query
// The query template with a placeholder query = "SELECT * FROM users WHERE username = ? AND password = ?"; // User input bound as data, never code execute(query, [userInput, passInput]);

How Parameterization Protects You

✕ Without Parameterization ' OR '1'='1 String concat Input = Code ALL rows returned ✓ With Parameterization ' OR '1'='1 Prepared stmt Input = Data only No match 0 rows returned The placeholder ? ensures user input is NEVER parsed as SQL syntax The query structure is compiled before any data is bound

How to Defend Against SQLi

1
Use Parameterized Queries. Always use prepared statements with bound parameters instead of string concatenation.
2
Validate and Sanitize Input. Reject unexpected characters (e.g., single quotes, semicolons) where they don't belong.
3
Apply Least Privilege. The database account your app uses should only have the permissions it needs: no DROP or ALTER rights.
4
Use an ORM or Query Builder. Frameworks like SQLAlchemy or Django ORM automatically parameterize queries for you.
5
Deploy a Web Application Firewall (WAF). A WAF can detect and block known SQLi patterns as an additional layer of defense.

Example 1: Login Bypass

A login form asks for a username and password. The server builds this query:

SELECT * FROM users WHERE username = '{input}' AND password = '{input}';

An attacker enters admin' -- as the username. The -- is a SQL comment, so everything after it is ignored:

SELECT * FROM users WHERE username = 'admin' -- ' AND password = '...'

Example 2: UNION-Based Data Theft

A product search page runs this query with the user's search term:

SELECT name, price FROM products WHERE name LIKE '%{search}%';

The attacker searches for: ' UNION SELECT username, password FROM users --

SELECT name, price FROM products WHERE name LIKE '%' UNION SELECT username, password FROM users --%'

Example 3: Destructive Payload

The same vulnerable search field can be exploited to destroy data:

// Attacker's input: '; DROP TABLE users; --

The server constructs:

SELECT name, price FROM products WHERE name LIKE '%'; DROP TABLE users; --%'

Fixing Each Example

✓ Login: Parameterized (Python)
cursor.execute( "SELECT * FROM users WHERE username = %s AND password = %s", (user_input, pass_input) )
✓ Search: Parameterized (JavaScript/Node)
db.query( "SELECT name, price FROM products WHERE name LIKE $1", [`%${searchTerm}%`] )

Common Mistakes

✕ Blacklist Filtering
Trying to block specific keywords like "DROP" or "UNION". Attackers easily bypass blacklists with encoding tricks and alternate syntax.
✕ Escaping Quotes Only
Manually escaping single quotes is error-prone and incomplete. Different databases have different escape rules: it is not a reliable defense.
✕ Client-Side Validation Only
JavaScript validation in the browser can be bypassed by any attacker. All validation must happen on the server side as well.

Defense-in-Depth Summary

Defense Layer What It Does Strength
Parameterized Queries Separates SQL code from data ★★★ Primary
Input Validation Rejects unexpected formats ★★ Secondary
Least Privilege Limits DB account permissions ★★ Secondary
ORM / Query Builder Auto-parameterizes queries ★★★ Primary
WAF Blocks known attack patterns ★ Supplementary
Error Handling Hides DB error details from users ★ Supplementary

Question 1 of 5

What is the root cause of SQL injection vulnerabilities?

Question 2 of 5

An attacker enters ' OR '1'='1 into a login form. What does this payload do?

Question 3 of 5

Which defense is considered the primary mitigation against SQL injection?

Question 4 of 5

In a UNION-based SQL injection, what does the attacker accomplish?

Question 5 of 5

Why is manually escaping single quotes considered an unreliable defense against SQL injection?