What is SQL injection? How it works and how to prevent it
SQL injection is one of the most common web vulnerabilities — this guide explains how it works, the main attack types, and the secure coding practices that prevent it.
On this page
- How SQL injection works
- Common attack types
- Classic (in-band) injection
- Blind SQL injection
- Second-order SQL injection
- UNION-based injection
- Potential damage
- How to prevent SQL injection
- 1. Parameterized queries (prepared statements)
- 2. Allow-list input validation
- 3. Least privilege
- 4. Object-relational mappers (ORMs)
- What does not reliably work
- Security in a larger picture
- FAQ
- What is SQL injection?
- Can parameterized queries always prevent SQL injection?
- What is blind SQL injection?
- How common is SQL injection in 2026?
- Summary
SQL injection is a code injection technique used to attack data-driven applications. It works by inserting malicious SQL statements into an entry field and having the database execute them as if they were part of the application's legitimate query. It is one of the oldest and most common web security vulnerabilities, and it can lead to stolen data, tampered records, and even full server compromise.
How SQL injection works
SQL injection happens when attacker-supplied data becomes SQL code. This occurs when a program builds a SQL query by string interpolation or by concatenating user-supplied data directly into the query string, instead of keeping data separate from the SQL instructions.
Consider a login form that builds a query like this:
SELECT * FROM users WHERE name = '<user input>' AND password = '<user input>'
If the application inserts the username directly into the string, then entering the username name' OR 'a'='a turns the query into:
SELECT * FROM users WHERE name = 'name' OR 'a'='a' AND password = '<user input>'
Because OR 'a'='a' always evaluates to true, the WHERE clause matches every row. The attacker logs in as the first user in the table — which is often the administrator. The root problem is that SQL makes no real distinction between the control plane (the query structure) and the data plane (the input values), so input can alter the structure of the query itself.
Common attack types
Classic (in-band) injection
The attacker injects SQL directly through an input field or URL parameter, and the database response appears directly in the application. This is the simplest form and often the first thing an attacker tries.
Blind SQL injection
The application does not return the database's error messages or query results directly, so the attacker cannot read the output. Instead, the attacker sends queries that produce a true or false result and observes how the page behaves in response. For example, sending 1=1 and 1=2 in a URL parameter and watching for a different page can reveal whether the site is vulnerable.
Second-order SQL injection
An application guards its SQL against immediate user input, but stores the data and later builds another query from the stored value without the same care. The first request is safe, but the stored data becomes dangerous when it is reused later.
UNION-based injection
The attacker uses the UNION SQL operator to append an extra SELECT to the original query, retrieving data from other tables — such as usernames, password hashes, or credit card numbers.
Potential damage
A successful SQL injection exploit can:
- Read sensitive data from the database, such as personal information, credentials, or payment details.
- Modify or delete data (Insert, Update, Delete), tampering with records or destroying data.
- Execute administrative operations on the database, such as shutting it down.
- Recover the contents of files present on the database server's filesystem.
- In some cases, issue commands to the operating system.
Shortly put, SQL injection can let an attacker spoof identity, tamper with existing data, void transactions, change balances, disclose all data on the system, or become an administrator of the database server.
How to prevent SQL injection
The reliable defenses follow a defense-in-depth approach. OWASP consistently warns against relying on string escaping or denylists as a primary defense because they are "frail compared to other defenses" and full of loopholes.
1. Parameterized queries (prepared statements)
This is the primary defense. Placeholders (also called bind variables) hold only values of a defined type, preventing input from altering the query structure. The application code stays separate from the data, and each parameter is passed as a distinct value. Most development platforms and database drivers support this directly — for example, Java's PreparedStatement, PHP's PDO, and the .NET SqlCommand with parameters.
SELECT * FROM users WHERE name = ? AND password = ?
The ? marks are placeholders. Even if an attacker types SQL into the name field, it is treated as a value, not as part of the query.
2. Allow-list input validation
Validate that input matches an expected pattern (an allow list) so that only explicitly allowed values are accepted. For identifiers, user names, sort keys, and other structured inputs, this blocks unexpected characters before they reach a query. Input validation alone does not prevent SQL injection, but it is an effective additional safeguard.
3. Least privilege
Give database accounts only the minimum permissions they need. A read-only account should not be able to modify data, and application accounts should never have administrative access. Limiting access to system tables and using separate accounts for different functions — such as authentication versus data modification — reduces the damage a single successful injection can cause.
4. Object-relational mappers (ORMs)
ORMs typically offer built-in protections against SQL injection because they parameterize queries for you. However, they are not a guarantee: raw SQL executed through an ORM can still be vulnerable if built by concatenating input. Treat ORM raw-query paths with the same care as hand-written SQL.
What does not reliably work
- String escaping — manually escaping special characters in input is widely discouraged. Not every piece of data can be safely added to SQL as a quoted string (for example,
LIMITclause arguments or table and column names), so escaping leaves other injection paths open. - Denylists / blacklists — blocking a list of known-bad characters or keywords is riddled with loopholes and can be bypassed with different encodings.
Security in a larger picture
SQL injection is one of many threats that fall under the general category of injection attacks. A layered approach — parameterized queries, strict input validation, least-privilege database accounts, and regular security testing — is what hardens an application in practice. For related concepts, see our guides on HTTP status codes and the HTTP method basics.
FAQ
What is SQL injection?
SQL injection is a code injection attack in which malicious SQL statements are inserted into an entry field so that a database executes them as part of a legitimate query. It happens when an application builds SQL by concatenating user input into the query string instead of keeping data separate from the SQL instructions.
Can parameterized queries always prevent SQL injection?
For the data values in a query, yes — parameterized queries keep input from altering the query structure, which is the primary defense. But they do not cover every use of SQL: database identifiers (table names, column names) and LIMIT clause arguments cannot always be parameterized, so those paths still need allow-list validation and careful handling.
What is blind SQL injection?
Blind SQL injection occurs when an application does not return query results or database errors directly. The attacker sends queries that evaluate to true or false and observes how the page responds, inferring information one bit at a time. It is slower than classic injection but equally exploitable.
How common is SQL injection in 2026?
SQL injection remains a consistently top-ranked vulnerability in web application security reports (OWASP and industry sources list injection as a long-standing high-impact class). It persists because it is easy to detect and easy to exploit, and any site with a database and dynamic queries can be a target regardless of size.
Summary
SQL injection is a code injection attack that occurs when user-supplied data is concatenated into a SQL query and executed as if it were part of the query structure. It can read, modify, or delete database data and, in severe cases, compromise the database server or operating system. The reliable defenses are parameterized queries, allow-list input validation, and least-privilege database accounts — applied together rather than relying on escaping or denylists. Because the flaw is easy to detect and exploit, any application that builds SQL queries with user input should treat prevention as mandatory, not optional.
Sources
- Wikipedia — SQL injection (en.wikipedia.org/wiki/SQL_injection
- CC BY-SA 4.0)
- OWASP — SQL Injection (owasp.org/www-community/attacks/SQL_Injection
- CC BY-SA 4.0)
- OWASP — SQL Injection Prevention Cheat Sheet (cheatsheetseries.owasp.org
- CC BY-SA 4.0)
Share this guide
Related guides
- What is authentication? Passwords, biometrics, SSO, and modern methods explained
Authentication is the process of verifying who you are. Learn how passwords, multi-factor authentication, biometrics, SSO, OAuth, and password managers work — and which methods offer the best protection for your application.
- What is CSRF (Cross-Site Request Forgery)? How it works and how to prevent it
Cross-Site Request Forgery (CSRF) tricks a logged-in browser into sending unwanted requests to a trusted site. This guide explains how the attack works and the defenses that stop it.
- What is SSRF (Server-Side Request Forgery)? How it works and how to prevent it
Server-Side Request Forgery (SSRF) lets an attacker abuse a server's own URL-fetching feature to reach internal systems and cloud metadata. This guide explains the attack and the defenses that stop it.