Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy SQL Injection
Beginner · 20 min

SQL Injection

Learn how attackers manipulate database queries and how parameterized queries stop them cold.

1 What is SQL Injection?

SQL Injection (SQLi) occurs when user-supplied data is embedded directly into a SQL query without sanitization. An attacker can break out of the intended query and execute arbitrary SQL, leading to data theft, authentication bypass, or full database compromise.

Vulnerable example (Python):

username = request.form['username']
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)

If the attacker sends ' OR '1'='1 as the username, the query becomes WHERE username = '' OR '1'='1', returning all rows and bypassing login.

2 Parameterized Queries — The Fix

The definitive fix is to use parameterized queries (also called prepared statements). The SQL template is compiled first; user data is passed separately and can never alter the query structure.

# Safe — Python with psycopg2
cursor.execute(
    "SELECT * FROM users WHERE username = %s",
    (username,)
)
// Safe — Java JDBC
PreparedStatement stmt = conn.prepareStatement(
    "SELECT * FROM users WHERE username = ?"
);
stmt.setString(1, username);

ORMs like SQLAlchemy, Hibernate, and ActiveRecord use parameterization by default when you use their query builder — but raw string interpolation bypasses those protections.

3 Second-Order & Blind Injection

Second-order injection happens when data is safely stored but later used unsafely in a query. Always parameterize on read, not just on write.

Blind injection is when the attacker gets no direct output but can infer data from timing differences or conditional behavior (e.g., SLEEP(5) if condition is true). Parameterized queries prevent this too.

Defense checklist:

  • Use parameterized queries / prepared statements everywhere
  • Apply least-privilege DB accounts (read-only where possible)
  • Enable WAF rules for SQLi patterns
  • Use SAST tools to flag string concatenation in SQL contexts

Knowledge Check

0/4 correct
Q1

What is the root cause of SQL injection vulnerabilities?

Q2

Which of these is the most reliable defense against SQL injection?

Q3

What is "second-order SQL injection"?

Q4

A developer escapes all single quotes before inserting into SQL. Is this sufficient?

Code Exercise

Fix the SQL Query

The function below is vulnerable to SQL injection because it concatenates user input. Rewrite it using a parameterized query with the `%s` placeholder (psycopg2 style).

python