Skip to content

Lesson 1 of 9 · 22m

How SQL Injection Really Happens

Injection is a parser confusion problem, not a magic payload — learn to spot concatenation, unsafe context, and the difference between data and control.

The first SQL injection you see in the wild rarely looks like ' OR 1=1--. It looks like a search endpoint that behaves slightly too broadly, an error page that leaks a fragment of SQL, or a report that sorts by a column name taken straight from the query string. Senior people learn to read those signals because injection is fundamentally a parser confusion problem: user-controlled data crossed a boundary and became grammar.

The broken boundary

# Python + psycopg, the classic mistake
sql = "SELECT id, email FROM users WHERE tenant_id = " + tenant_id
cur.execute(sql)

The database does not know that tenant_id came from an HTTP request. It receives one string and parses it as SQL. If tenant_id is 42 OR tenant_id = 7, the parser accepts it as part of the predicate. Nothing about the database is malfunctioning — the application assembled an untrusted program.

Injection context decides everything

A payload that works in a string literal fails in an integer comparison, and both fail when the value is used as an identifier:

-- string context
WHERE email = 'alice@example.test'

-- numeric context
WHERE tenant_id = 42

-- identifier context: cannot be parameterized as a normal value
ORDER BY created_at DESC

This is why “just escape quotes” is not a defense. You have to know whether the input is being used as a string, number, boolean expression, table name, column name, or keyword.

What experienced testers look for

  • Responses that change when input is syntactically valid versus invalid SQL.
  • Database error text, especially partially normalized errors in logs or debug pages.
  • Behavior differences after ' or " in string fields.
  • Numeric parameters that accept expressions or trailing SQL fragments.
  • Sort, filter, and column-selection parameters that are mapped unsafely.

The day-one mental model

Never ask “is this input malicious?” Ask “what SQL will the database parse after this input is inserted?” If you cannot answer precisely, you do not understand the query construction path yet.

Field notes

  • Injection often survives input validation because validation answers the wrong question: “is this a plausible value?” instead of “can this become syntax?”
  • WAFs and ORMs change the shape of exploitation; neither changes the underlying boundary violation.
  • Stored procedures can be injectable too if they concatenate SQL internally.
  • Treat all SQL construction as code generation. Review it with the same suspicion you would apply to eval.

Was this lesson helpful?

Sign in to rate