Beginner

What Is SQL Injection?

SQL injection is a web application vulnerability...

15 min 14 sections
1

Introduction

What Is SQL Injection?

i

Introduction

SQL injection is a web security vulnerability in which an attacker manipulates a SQL query by supplying malicious input that the application inserts directly into the query, instead of treating it strictly as data.

Injection has appeared in the OWASP Top 10 for Web Applications in every edition since the very first one in 2003, where it ranked #6. It held the #1 spot for a decade — the 2010, 2013, and 2017 editions — before dropping to #3 in 2021, and to #5 in the current 2025 edition. That decline reflects how widespread proper defenses like parameterized queries have become, not that injection stopped being dangerous — it remains one of the most consistently exploited vulnerability classes in real applications today.

2

Objectives

Learning Objectives

🎯

Learning Objectives

By the end of this lesson, you should be able to:

1. Define SQL injection and how the vulnerability occurs.

2. Explain how user input can influence SQL queries in an insecure application.

3. Identify common locations where SQL injection vulnerabilities can occur.

4. Describe the major types and potential impact of SQL injection.

5. Understand the basic approach to detecting SQL injection vulnerabilities.

6. Explain how parameterized queries and other defensive controls prevent SQL injection.

3

Concept

SQL Injection in Simple Terms

The vulnerability exists at the point where untrusted input is incorporated into the SQL query in an unsafe manner.

Consider the following normal flow of a typical web application:

User Input → Application → SQL Query → Database → Result → Application Response


In a SQL injection vulnerability, an application incorporates untrusted user input into a SQL query in an unsafe way. An attacker can craft input that changes the intended structure or logic of a SQL query.


If the attacker can cause their input to be interpreted as part of the SQL statement and thereby alter the query's intended behavior, the application is vulnerable to SQL injection.

Normal situation: User input = Data

SQL injection situation: User input = influences SQL syntax/logic

4

Concept

How Web Applications Interact With Databases

Following is a typical architecture of the application:

Browser -> HTTP Request -> Web Application -> Application Code -> SQL Query -> Database -> SQL Result -> Application -> HTTP Response -> Browser

HTTP Request:

Message send by client server to the web server for asking data or uploading or updating data.
Http request has four important parts: HTTP Method, URL, Header and Body.

HTTP Method: With the help of http method browser tell server what they want. Following are the types of http methods.

GET : Used when client want data from the server(Loads a web page)
POST: Used when client want to send data to the server(Submitting a form or writing post)
PUT: Used when client want to update or replace complete record or data from server.
PATCH: Used when client want to update or replace particular record from the server.
DELETE: Used when client want to delete record from server.

URL:
GET /info/page1
Complete URL: https://example.com/info/page1

Headers: Provide additional information.
For Example:
Host: example.com <-- Name of the host
User-Agent: Chrome <-- Tells which type of client making request.
Accept: text/html <-- Type of content
Accept-Language: en-US <-- Language of the content

Body:
Request may contain body when submitting form

POST /login
email= email@example.com
password=***************

5

Explanation

How SQL Injection Happens

A SQL injection vulnerability occurs when an application dynamically constructs a SQL query using untrusted user input and fails to properly separate the input from the SQL statement.

A typical vulnerable flow looks like this:

User Input Application receives input → Application constructs SQL query SQL Query + User-Controlled Data Database interprets the query Result


Consider following query :
SELECT * FROM products WHERE name = 'Mobile';

The security vulnerability arises when an application directly concatenates user-supplied input into an SQL query.

An attacker can exploit this by supplying specially crafted input that alters the intended logic of the original SQL query.
query = "SELECT * FROM products WHERE name = '" + user_input + "'";

The problem is the construction pattern: untrusted input is being directly incorporated into the SQL statement.

6

Example

Anatomy of a Vulnerable SQL Query

Example

A common vulnerable programming pattern is:

$sql = "SELECT * FROM products WHERE name = '" . $userInput . "'";

Here user-controlled input = '" . $userInput . "'"

If $userInput = mobile then,
$sql = SELECT * FROM products WHERE name = 'mobile';

The input is directly incorporated into the SQL statement, specially crafted input may be able to influence the SQL syntax or logic.

if $userInput = mobile' OR '1'='1 then,
$sql = SELECT * FROM products WHERE name = 'mobile' OR '1'='1'";


Final query actually doesOR '1'='1' is always true, so the WHERE clause matches every row regardless of the name filter, meaning this returns the entire products table instead of just "mobile."

7

Explanation

Trusted Data vs. Untrusted Input

What is trusted data?

Data which is controlled, validated, or generated by a trusted component of the system.

Example:
1. A database-generated record ID.
2 Value generated internally by the application.
3. Predefined configuration value.
4. Value selected from a server-controlled allowlist.
5. Input checked against a strict, known-safe format before use (e.g., an ID matched against ^[0-9]+$).


What is untrusted input?

Data that originates from a source that an attacker may be able to control or influence.

Example:
1. URL parameters
2. Form fields
3. File names
4. API parameters
5. Search queries
6. HTTP headers
7. Cookies


Why this matters for SQL injection:

Consider the following code:

$userInput = $_GET['name'];
$sql = "SELECT * FROM products WHERE name = '" . $userInput . "'";


Here, the application has failed to maintain a reliable separation between SQL instructions and user-controlled data. $_GET['name'] is untrusted — it comes directly from the URL, which an attacker fully controls — yet it's concatenated straight into the query as if it were fixed, trusted text.

8

Concept

How User Input Changes SQL Query Logic

Consider the following poorly constructed query:

$sql = "SELECT * FROM users
WHERE username = '" . $username . "'
AND password = '" . $password . "'";

Here, the problem is that the application is allowing user-controlled values to become part of the SQL statement itself.
If specially crafted input is accepted, characters supplied by the attacker can affect how the resulting SQL statement is parsed.

This can potentially change:

* conditions
* operators
* grouping
* comparisons
* filtering logic
* the overall meaning of the query

Attacker will manipulate query like this:

SELECT * FROM users WHERE username = 'Bob' OR '1'='1' -- ' AND password = '...'

'1'='1' will evaluate into TRUE
Hence, 'Bob' OR '1'='1'" will evaluate into TRUE, text after -- will be neglected.

The application should maintain a clear boundary between SQL structure and user supplied data.

9

Impact

What Can an Attacker Do With SQL Injection?

💥

Impact

The impact of SQL injection depends on the database privileges, application functionality, and type of SQL injection vulnerability.


Bypass authentication — potentially access accounts without valid credentials.
Read sensitive data — retrieve information such as usernames, personal data, or application records.
Modify data — alter database records when the database account has write privileges.
Delete data — delete records or damage application data.
Access other database tables — retrieve information beyond the application's intended functionality.
Extract database structure — discover table names, columns, and other database metadata.

10

Concept

Types of SQL Injection

Classified based on how the attacker interact with application and how information is obtained.

1. In-Band SQL Injection: UNION-based SQL injection and Error-based SQL injection.
2. Blind SQL Injection: Boolean-based blind SQL injection and Time-based blind SQL injection.
3. Out-of-Band SQL Injection
4. Second-Order SQL Injection

11

Explanation

In-Band, Blind, and Out-of-Band SQL Injection

Classified based on how the attacker interact with application and how information is obtained.

1. In-Band SQL Injection:
Attacker uses the same communication channel to inject the SQL and receive the results.

Two sub type:
UNION-based SQL injection — uses SQL UNION operations to retrieve data through the application's normal response.
Error-based SQL injection — relies on database error messages to obtain useful information.


2. Blind SQL Injection:
In blind SQL injection the attacker tries to infers information from the application's behaviour.

Two sub type:
Boolean-based blind SQL injection — Attacker try to generate different condition based on Boolean operator.
Time-based blind SQL injection — Observes differences in response time caused by database operations.


3. Out-of-Band SQL Injection:
The attacker causes the database to send information through a separate communication channel, rather than normal request response.


4. Second-Order SQL Injection:
In this type, the attacker first stores malicious code into the database first and later use that payload to manipulate application.

12

Vulnerability

Where SQL Injection Can Occur

⚠️

Vulnerability

SQL injection can occur wherever user-controlled or untrusted data is incorporated into a SQL query in an unsafe manner.


URL/query parameters — e.g., search, product ID, or page parameters.
Form fields — usernames, search fields, filters, and other submitted values.
HTTP request bodies — including JSON or form-encoded API requests.
Cookies — when cookie values are later used in database queries.
HTTP headers — when application-controlled headers are incorporated into SQL queries.
API parameters — query parameters, path parameters, or request-body fields.
Hidden form fields — hidden does not mean trusted; attackers can modify them.
Stored application data — data originally supplied by users may later become dangerous when reused in another SQL query.

13

Detection

How SQL Injection Vulnerabilities Are Identified

🔎

Detection

SQL injection vulnerabilities are identified by tracing untrusted input to database queries and determining whether that input can influence SQL syntax, logic, or execution.

1. Identify Input Points: URL parameters, Form fields, API parameters, JSON request bodies, Cookies, HTTP headers, Hidden fields etc

2. Trace the Input: Determine whether the input eventually reaches a database query.

3. Observe Application Behavior:
Database error messages.
Changes in application responses
Different results for logically different inputs
Unexpected authentication behavior
Significant response-time differences

4. Review the Application Code:
During source-code review, look for unsafe query construction patterns such as:
$sql = "SELECT * FROM users WHERE id = " . $userInput;

5. Use Automated Security Testing Tools:
Tools such as Burp Suite and OWASP ZAP can help identify suspicious input points and automate portions of security testing.

14

Remediation

Basic SQL Injection Prevention

🛡️

Remediation

The primary defense against SQL injection is to keep SQL instructions separate from user-supplied data by using parameterized queries.

1. Use Prepared Statement with Parameterized Queries: Use SQL Query with Parameter + User Input

2. Use Safe Database APIs: Use your framework's database abstraction layer or ORM correctly rather than manually constructing SQL strings with user input.

3. Validate Input: Apply appropriate server-side input validation.

4. Apply Least Privilege: The application's database account should have only the permissions it actually needs.

5. Handle Database Errors Safely: Do not expose detailed database errors to users in production.