How it works
Imagine a search page that builds its query by joining the typed text into a longer SQL string. If a visitor types text that contains SQL syntax, the database cannot tell which part was the developer's instruction and which part was data, so it runs all of it. The visitor has rewritten the query. This example is hypothetical.
Why it still happens
It has been well understood for a long time, yet it still appears: in older code, in hand-written reporting queries and wherever a developer bypassed the framework just this once. It belongs to the injection theme of the OWASP Top 10.
How to prevent it
- Use parameterised queries, also called prepared statements. The query text and the values travel separately, so input is only ever data.
- Use an ORM or query builder properly. Their raw-query escape hatches are risky when you insert variables into the string.
- Allowlist what cannot be a parameter, such as a column name or a sort direction, by matching it against a fixed list.
- Give the application a limited database account, so a flaw cannot drop tables or read everything.
- Validate input for type and length as a second layer, never as the only defence.
Common mistakes
- Trying to clean input by removing quotes. Filters get bypassed; parameters do not.
- Trusting a check that runs only in the browser.
- Showing raw database errors to users, which hands attackers a map.
- Assuming internal tools and admin pages do not need the same care.
Related terms
A secure code review looks for string-built queries, and a penetration test tries to exploit them. Its cousin in the browser is cross-site scripting.