SQL injection

On this page 7

SQL injection is a vulnerability in which untrusted input is inserted into a database query in a way that changes the query’s structure, allowing an attacker to read, modify or delete data, bypass authentication or, in some configurations, run commands on the database server. In application security it is the textbook example of an injection flaw: the application mixes code and data in one string and lets the database interpret attacker-controlled text as SQL.

The flaw has been understood for decades and has a reliable fix, parameterized queries, yet it still appears in custom code, legacy systems, stored procedures and reporting features. It belongs to the injection category of the OWASP Top 10 and is tracked as CWE-89.

How SQL injection alters a query

SQL injection happens when an application builds a query by string concatenation. Suppose a login check is assembled as SELECT * FROM users WHERE name = ' plus the user name plus '. If the user name is admin' --, the quote closes the string literal and the double dash turns the rest of the query into a comment, so the password condition disappears.

The database cannot tell which part of the text the developer intended and which part the attacker supplied. It simply parses the final string and executes it. Any input that reaches a query this way, including form fields, URL parameters, headers, cookies and JSON bodies, is a potential injection point.

Parameterized queries remove the problem by sending the query structure and the values separately. The database compiles SELECT * FROM users WHERE name = ? first and then binds the value as pure data, so a quote or a keyword inside it can never change the query’s logic.

Types of SQL injection

SQL injection variants differ in how the attacker receives results. The table shows the main classes used in testing and in real attacks.

TypeHow data is extractedTypical signal
In-band, error-basedDatabase error messages reveal dataDetailed SQL errors in the response
In-band, UNION-basedExtra rows appended with UNION SELECTInjected values appear on the page
Blind, boolean-basedTrue and false conditions change the pageSmall differences in content or length
Blind, time-basedConditional delays such as sleep functionsResponse time grows by a fixed amount
Out-of-bandDatabase sends data over DNS or HTTPOutbound requests from the database host
Second-orderStored input is used unsafely in a later queryEffect appears in a different feature
Main classes of SQL injection

Blind techniques are slower, extracting data one bit or one character at a time, but automated tools make them practical. Second-order injection is the hardest to find because the unsafe query runs later, often in an administrative or batch process that testers do not exercise.

Impact of SQL injection on data and systems

The impact of SQL injection depends mostly on the privileges of the database account the application uses and on the database engine’s features. An application that connects as a database administrator turns a single injectable parameter into full control of the data store.

ConditionPossible attacker outcome
Read access onlyTheft of customer data, password hashes, secrets
Write accessModified prices, created accounts, planted content
Stacked queries supportedArbitrary additional statements, data deletion
Excessive server privilegesFile reads, file writes, operating system commands
Shared database across applicationsCompromise spreads beyond the vulnerable application
Impact depending on context

Authentication bypass, as in the login example above, is the most visible effect, but bulk data theft is the most common goal. Because the attack uses legitimate application traffic, it often leaves little trace unless query logging or database activity monitoring is in place.

SQL injection compared with other injection flaws

SQL injection shares its root cause with other injection flaws in application security: an interpreter receives mixed code and data. What differs is the interpreter and therefore the impact.

VulnerabilityInterpreter targetedPrimary victimMain defense
SQL injectionDatabase SQL engineServer-side dataParameterized queries
XSSBrowser HTML and JavaScriptOther users of the siteContext-aware output encoding, CSP
NoSQL injectionDocument database query operatorsServer-side dataTyped queries, operator filtering
OS command injectionSystem shellServer hostAvoid shells, use argument arrays
LDAP injectionDirectory query filtersIdentity dataFilter escaping, parameterized APIs
SQL injection and related vulnerabilities

Unlike CSRF, which abuses a victim’s authenticated browser to send valid requests, SQL injection changes the meaning of a request on the server. The two can combine, but they require different defenses.

Preventing SQL injection in practice

The primary defense is parameterized queries or prepared statements for every value that reaches SQL. Most object-relational mappers parameterize automatically, but their raw query and string-format features reintroduce the risk when developers use them with concatenated input.

  • Never concatenate input into SQL, including in stored procedures that build dynamic SQL.
  • Allow-list identifiers such as column names and sort directions, because placeholders cannot bind them.
  • Apply least privilege to the database account: no administrative rights, no file or command functions.
  • Suppress detailed database errors in responses and log them on the server instead.
  • Test with SAST and DAST tools and review every raw query during code review.

Escaping and input filtering are weak substitutes. Escaping depends on character sets and database dialects, and blacklists of keywords are routinely bypassed with encoding, comments or case variations. A web application firewall can block common payloads, but it is a compensating control, not a fix.

Stripped to the essentials

Imagine a clerk who follows written instructions exactly. A form says: “Give the customer the file named ____.” A visitor writes in the blank: “Smith, and also every other file in the cabinet.” A careless clerk reads the whole line as one instruction and hands everything over.

SQL injection is the same mistake inside software. The program lets a visitor’s text become part of its instructions to the database. The fix is to keep the instruction and the visitor’s answer on separate sheets, so the answer is always treated only as a name.

Where it is applied

An online shop has a product search page that sorts results by a column name taken from the URL. During a scheduled security assessment, a tester notices that adding a quote to the sort parameter produces a database syntax error in the page.

Using a time-based blind technique, the tester confirms that a conditional delay of five seconds is executed, which proves that the parameter is injectable. The application account can read the customer table, including email addresses and password hashes, so the finding is rated critical.

The developers replace the concatenated sort clause with an allow-list of permitted column names and convert the remaining queries to parameterized statements. They also remove unnecessary privileges from the database account. A retest shows that the payloads now have no effect on the query.