SQL injection has been understood for more than twenty years, appears in every list of common web vulnerabilities, and is still found in new code every year. It persists not because the fix is difficult β the fix is straightforward β but because the vulnerable pattern looks so natural: take some input, put it into a string, send the string to the database.
This guide explains the mechanism from the ground up, so that the fix makes sense rather than being a rule to memorise. Once you see why the problem happens, it becomes easy to spot the places in a codebase where it can still creep in, including in code that uses an ORM and feels safe.
The mechanism: data that becomes code
A database receives SQL as text and parses it into a command. When an application builds that text by concatenating fixed SQL with user input, the input becomes part of the command before the database ever sees it. If the input contains characters that are meaningful in SQL β a quote that ends a string, a keyword, a comment marker β the database has no way to know those characters came from a user rather than from the developer.
That is the whole vulnerability: user-supplied data crossing the boundary into code. The same shape appears elsewhere β in shell commands, HTML, template engines and, more recently, in prompts sent to language models β which is why understanding it once pays off many times.
A concrete case
Imagine a login check built by inserting the submitted username and password into a query string that selects a user whose name and password match. A user who types an ordinary name produces an ordinary query. But a user who types a name containing a quote, followed by a condition that is always true and a comment marker, can change the structure of the query so that the password check is cut off and the condition matches any row.
The details vary between databases, but the principle does not: the attacker is not guessing a password, they are rewriting the question the application asks the database. Depending on how the query is built and what the database user is allowed to do, the same technique can read other tables, modify data or delete it.
Why escaping is not the answer
An intuitive fix is to βcleanβ the input: escape quotes, strip suspicious characters, block keywords. This approach has a long history of failure. Escaping rules differ between databases, character encodings and contexts within a query; numbers, identifiers and strings need different handling; and attackers are endlessly inventive in finding the case a filter missed.
Blocklists of dangerous words fail in a different way: they reject legitimate input, such as names and text containing apostrophes, while still missing the variants attackers use. Trying to make untrusted text safe to paste into code is fighting the problem at the wrong layer.
Parameterized queries: keeping data as data
The real fix is to never mix data into the SQL text at all. With a parameterized query β often called a prepared statement β the application sends the SQL with placeholders where values will go, and sends the values separately. The database parses the command first, from the fixed text alone, and only then binds the values as data.
Because the structure of the query is fixed before the values arrive, nothing in a value can change it. A username containing quotes and keywords is simply compared, literally, with the usernames in the table. This is why parameterized queries are not a filter that might miss something: they remove the mechanism the attack depends on. Every mainstream database driver supports them, and they should be the default for every query that includes a value from outside the code.
The parts of a query that cannot be parameters
Placeholders can stand in for values, but usually not for structural parts of a query: table names, column names, sort directions or SQL keywords. This is where injection most often survives in modern code β a sort parameter from a URL inserted directly into an ORDER BY clause, or a column name chosen by the user for a filter.
The safe pattern for these cases is an allowlist. Map the userβs choice to a fixed set of known-good identifiers in code β for example, accept only βnameβ, βdateβ or βpriceβ and translate each to a specific column β and reject anything else. Never pass a user-supplied identifier into the query text, however it has been cleaned.
ORMs and query builders: mostly safe, not automatically
Object-relational mappers and query builders generate parameterized SQL for their normal operations, which is a large part of why injection is less common than it once was. But almost every ORM also offers a way to run raw SQL or to insert raw fragments into an otherwise generated query, for the cases the abstraction does not cover.
Those escape hatches are where vulnerabilities hide. A raw query built with string formatting is exactly as vulnerable inside an ORM as outside it. Most ORMs provide a parameterized form of their raw-query function; use it, and treat any string interpolation into SQL as a code-review red flag, whatever layer it appears in.
Stored procedures are not a cure
It is sometimes said that stored procedures prevent injection. They help only if they are called with parameters and do not themselves build dynamic SQL from their inputs. A stored procedure that concatenates its arguments into a string and executes it is vulnerable in exactly the same way as application code that does so.
The rule is the same everywhere: wherever SQL text is assembled, values must travel separately as parameters, and identifiers must come from an allowlist.
Limiting the damage: least privilege
Defence in depth assumes that one day something will slip through. The database account your application uses should have only the permissions it needs: if the application never drops tables or reads the audit schema, its account should not be able to. Separate accounts for different services, and read-only accounts for reporting, shrink what any single injection can reach.
Error handling matters too. Detailed database errors shown to users can reveal table names, query structure and versions that help an attacker refine an attack. Log full errors internally, and show users a generic message.
Finding injection in existing code
Search the codebase for places where SQL strings are built with concatenation or formatting, and for uses of raw-query functions. Pay particular attention to dynamic sorting, filtering, search features, reporting tools and administrative pages, which are often written quickly and reviewed lightly.
Static analysis tools and linters for many languages can flag string-built queries automatically, and security scanners can probe a running application. Neither replaces the habit of reviewing every query that includes outside input, but both catch mistakes that human reviewers miss on a busy day.
Testing your own code
For each endpoint that takes input used in a query, write tests that pass values containing quotes, comment markers and SQL keywords, and assert that the application treats them as ordinary text: a search for a name with an apostrophe should find the person, not throw an error or return everything.
Tests like these document the expected behaviour and guard against regressions when someone later βoptimisesβ a query by building it as a string. They are cheap to write and turn an abstract security rule into something the build enforces.
Where the rule stops applying
Parameterization protects the structure of a query, but it does not decide whether a user should be allowed to see or change the data the query touches. An endpoint that safely fetches an order by ID is still broken if it lets any user fetch any order by guessing IDs. Authorisation checks are a separate, equally important layer.
And the principle extends beyond SQL. Shell commands should be run with argument arrays rather than built strings; HTML should be produced by templating systems that escape by context; and any system that combines instructions with untrusted text, including prompts to language models, needs the same suspicion about data that becomes code.
Second-order injection
Injection does not always happen at the point where input arrives. In a second-order attack, a malicious value is stored safely β perhaps through a properly parameterized insert β and then later read back and inserted into a different query by code that assumes anything already in the database must be trustworthy.
The lesson is that βtrustedβ is about where SQL text is built, not where data came from. Data read from your own tables, from configuration, from another internal service or from a file deserves exactly the same treatment as data from a form: values go in as parameters, identifiers come from allowlists.
In short
SQL injection happens when user input is pasted into SQL text, letting data become part of the command. Escaping and blocklists try to fix the input and keep failing; parameterized queries fix the mechanism by sending values separately from the code.
Use parameters for every value, allowlists for every identifier, the parameterized forms of ORM raw queries, least-privilege database accounts and generic error messages. Review string-built queries as red flags, test with hostile input, and remember that safe queries still need proper authorisation checks.