SQL Injection
1. Introduction
SQL Injection (SQLi) is a web application vulnerability that occurs when an application incorporates user-controlled input into SQL queries without handling it safely.
SQL queries allow applications to interact with databases. When input is processed incorrectly, it may change the logic of a query and cause the application to behave in unintended ways.
Depending on the vulnerability and database permissions, SQL injection may allow unauthorized data access, authentication bypass, or modification of database records.
This writeup covers the major concepts in the SQL Injection learning path from PortSwigger Web Security Academy, including detection, UNION attacks, blind SQL injection, database identification, and prevention.
Learning resource: PortSwigger SQL Injection Learning Path
2. Understanding SQL Injection
Consider a simple SQL query used to retrieve products from a database:
SELECT * FROM products
WHERE category = 'Books';The application returns products belonging to the Books category.
A vulnerability may occur when an application constructs SQL queries by concatenating user input directly into a query string.
The core problem is that the database may interpret part of the input as SQL syntax instead of treating the entire input as data.
The important distinction is:
- Safe handling: User input is supplied as a parameter.
- Unsafe handling: User input changes the structure or logic of the SQL statement.
SQL injection is therefore primarily a problem of how applications construct and execute database queries.
3. Detecting SQL Injection Vulnerabilities
The first step in testing for SQL injection is identifying inputs that may influence database queries.
Potential entry points include:
- URL query parameters
- Search fields
- Login forms
- Product filters
- Cookies
- HTTP headers
- JSON and XML request bodies
Testing for unusual behavior
A tester can compare a normal request with carefully controlled test inputs.
For example, a single quote character may reveal an error if the application handles SQL strings incorrectly.
However, an error alone does not prove that SQL injection exists.
Look for repeatable differences such as:
- Database-related error messages
- Changes in returned content
- Unexpected HTTP status codes
- Different responses to logically different conditions
- Consistent response delays
A useful methodology is to record a baseline request, change one input at a time, and compare the responses.
SQL injection in different parts of a query
SQL injection is not limited to string values in a WHERE clause. Depending on how an application constructs its queries, user input may affect other parts of a statement, including sorting expressions or other query components.
The appropriate testing method depends on the context in which the input is used.
4. Retrieving Hidden Data
Applications sometimes use SQL queries to filter records according to user-selected categories or other parameters.
For example:
SELECT * FROM products
WHERE category = 'Books'
AND visible = TRUE;The application may intend to show only products that belong to a particular category and are marked as visible.
If the query is vulnerable, its logic may be altered so that records normally hidden from users are returned.
The security impact depends on the query, the application, and the database permissions.
Key lesson: A filter in the user interface is not a reliable security boundary unless access to the underlying data is also properly controlled.
5. Subverting Application Logic
SQL injection can also affect application logic.
For example, an application might check credentials with a query conceptually similar to:
SELECT * FROM users
WHERE username = ?
AND password = ?;If the application constructs this query unsafely, an attacker may be able to interfere with the conditions used for authentication.
This can potentially lead to authentication bypass.
The key issue is not the appearance of the login form. It is whether the server safely constructs and evaluates the database query.
Applications should use parameterized queries and established authentication mechanisms instead of building SQL statements from untrusted strings.
6. SQL Injection UNION Attacks
The SQL UNION operator combines the results of two or more SELECT queries.
For example:
SELECT name, category FROM products
UNION
SELECT name, category FROM archived_products;This combines rows from both queries into a single result set.
In a vulnerable application, a UNION-based SQL injection may allow the results of another query to appear in the application’s response.
Requirements for UNION
The queries combined with UNION generally need to satisfy two important requirements:
- Both queries must return the same number of columns.
- Corresponding columns must have compatible data types.
These requirements explain why a UNION attack cannot always be constructed immediately.
Determining the number of columns
The number of columns returned by the original query is important because a compatible UNION query must return the same number.
In an authorized lab, this can be investigated by observing how controlled test queries affect the response.
Finding a column with a suitable data type
Even when the column count is known, the data types must be compatible.
For example, a column containing text may be suitable for displaying a username, whereas a numeric column may not accept an arbitrary text value.
The general learning process is to establish the column count, understand the relevant data types, and observe how the application presents query results.
7. Retrieving Data from Other Tables
A database often contains multiple tables that serve different purposes.
For example:
TablePurposeproductsProduct informationusersUser accountsordersCustomer orderscategoriesProduct categories
A vulnerable query may expose data from tables that the application did not intend to display through that page.
The potential impact can include unauthorized access to personal or business information.
This is one reason database permissions should be restricted to the minimum required for each application component.
8. Retrieving Multiple Values from One Column
Sometimes the original query returns only one suitable column.
In certain database systems, string concatenation can combine several values into a single string.
For example, conceptually:
username + separator + emailThe separator helps distinguish one value from another when they appear together.
The exact concatenation syntax varies between database systems. Therefore, identifying the database type can be important when studying SQL injection behavior.
9. Examining the Database
Understanding the database structure can help explain how an application stores and retrieves information.
Two important questions are:
- Which database management system is being used?
- Which tables and columns exist in the database?
Identifying the database type
Different database systems have their own syntax and built-in functions.
Common examples include:
- MySQL
- Microsoft SQL Server
- PostgreSQL
- Oracle Database
Differences in syntax can help identify the database system when testing a controlled lab.
Database metadata
Database systems often provide metadata that describes the database structure.
Depending on the system and permissions, this metadata may reveal information about tables, columns, and other database objects.
Understanding database metadata is useful for both database administration and security testing.
Important: Database-specific syntax is not universal. A query that works on one database may fail on another.
10. Blind SQL Injection
Blind SQL injection occurs when an application is vulnerable to SQL injection but does not directly return the results of the relevant query or detailed database errors.
The application may appear to respond normally even when its database query has been affected.
Get Shadow’s stories in your inbox
Join Medium for free to get updates from this writer.
In this situation, testers must rely on indirect evidence.
Common forms include:
- Boolean-based testing
- Conditional error behavior
- Time-based behavior
- Out-of-band interactions
Boolean-based behavior
A boolean condition evaluates to either true or false.
A tester can compare responses to controlled conditions and determine whether the application’s behavior consistently reflects the result.
For example, the application might return different content depending on whether a condition evaluates to true or false.
Consistent differences can provide evidence of a SQL injection vulnerability.
Conditional errors
Some applications handle database errors differently depending on what happens during query execution.
If a controlled condition consistently causes a particular error behavior, that difference may reveal information about the query.
However, errors should be interpreted carefully because unrelated application failures can produce similar symptoms.
Time-based behavior
Some database expressions can cause a query to pause.
If an application is vulnerable, a controlled test may cause a repeatable delay even when the response contains no useful database output.
A single slow request is not sufficient evidence. Network latency, server load, and other factors can also affect response times.
Out-of-band testing
Out-of-band application security testing, or OAST, uses a separate communication channel to detect certain interactions.
This may help identify vulnerabilities when the application’s normal HTTP response does not reveal what happened in the database.
The observed interaction must be correlated with the controlled test before drawing conclusions.
11. SQL Injection in Different Contexts
SQL injection can occur in inputs other than ordinary URL parameters.
For example, an application might accept structured data in JSON or XML and then use that data to construct a SQL query.
The request format does not automatically make the application safe.
Security testers should understand how the server parses the request and how the resulting values are used in database queries.
Encoding and filtering
Applications may decode or transform incoming data before processing it.
For this reason, security testing must consider how input is handled across the entire processing chain.
Simple keyword filtering is not a dependable defense against SQL injection. Correct query construction is much more important than attempting to block individual SQL keywords.
12. Second-Order SQL Injection
Second-order SQL injection occurs when input is stored first and later used unsafely in a SQL query.
The initial action may appear harmless because the input is only saved.
The vulnerability becomes relevant when another part of the application retrieves that stored value and incorporates it into a new query without proper parameterization.
Conceptually:
User input
↓
Stored in the database
↓
Retrieved later
↓
Used unsafely in a new SQL query
↓
Unexpected query behaviorThis illustrates why security testing should examine how data moves through an application, not only what happens when a form is submitted.
Input that was previously stored should still be treated as untrusted data.
13. How Burp Suite Helps with SQL Injection Testing
Burp Suite provides useful tools for inspecting and comparing HTTP traffic during authorized security assessments.
Proxy
Burp Proxy allows testers to inspect requests and responses between the browser and the application.
It helps identify parameters, cookies, headers, and request-body fields.
HTTP history
HTTP history records requests and responses, making it easier to identify which input was submitted and what the application returned.
Repeater
Repeater allows a captured request to be sent again after controlled modifications.
This is useful for comparing a baseline request with a test request.
A careful workflow is:
- Capture a normal request.
- Send it to Repeater.
- Change one input.
- Send the request again.
- Compare the response status, body, and timing.
- Repeat to confirm that the behavior is consistent.
Changing one variable at a time makes the results easier to interpret.
14. Preventing SQL Injection
The most important defense against SQL injection is to ensure that user input cannot change the intended SQL query structure.
Parameterized queries
Parameterized queries separate SQL code from user-supplied values.
For example, in Java:
String query =
"SELECT * FROM products WHERE category = ?";PreparedStatement statement =
connection.prepareStatement(query);statement.setString(1, category);
The category is passed as a parameter instead of being concatenated directly into the query string.
This helps the database treat the value as data rather than executable SQL syntax.
Additional defenses
- Use parameterized queries or prepared statements.
- Avoid concatenating untrusted input into SQL statements.
- Use allowlists for dynamic identifiers such as table names or sort fields.
- Apply least-privilege permissions to database accounts.
- Avoid displaying detailed database errors to end users.
- Test applications regularly for security vulnerabilities.
- Use secure frameworks and database libraries.
- Review stored values when they are later used in queries.
Input validation can provide additional protection, but it should not replace parameterized queries.
15. Common Mistakes During SQL Injection Testing
Assuming every error proves a vulnerability
An error may result from unrelated application logic. Additional evidence is needed.
Ignoring the original response
A baseline response provides a reference for understanding whether the test changed the application’s behavior.
Testing only URL parameters
Cookies, headers, JSON fields, and other inputs may also influence database queries.
Relying on a single timing result
One delayed response may be caused by normal performance variations. Repeatable comparisons are more reliable.
Forgetting database differences
Different database systems support different functions and syntax.
Confusing detection with confirmation
A suspicious response is a clue. A well-supported finding requires repeatable evidence that connects the input to the unexpected query behavior.
16. SQL Injection Testing Workflow
The following workflow summarizes the main concepts:
Understand the application
↓
Identify database-related inputs
↓
Record a baseline request
↓
Test input handling
↓
Compare application responses
↓
Investigate relevant SQL behavior
↓
Confirm the finding
↓
Document impact and evidence
↓
Recommend remediationTesting should remain within the scope of an authorized lab or security assessment.
17. Key Takeaways
The major lessons from the SQL Injection learning path are:
- SQL injection happens when user input can interfere with SQL query construction.
- A vulnerability may affect data retrieval, authentication, or other application behavior.
- UNION attacks depend on compatible column counts and data types.
- Database metadata can describe tables and columns.
- Blind SQL injection relies on indirect observations rather than directly returned query results.
- Boolean, conditional-error, time-based, and out-of-band techniques provide different forms of evidence.
- Second-order SQL injection can occur when stored input is used unsafely later.
- Burp Suite helps inspect requests and compare responses.
- Parameterized queries are a primary defense against SQL injection.
- Reliable testing requires controlled experiments, repeatable results, and careful interpretation.
Conclusion
The SQL Injection learning path provides a foundation for understanding how web applications interact with databases and how unsafe query construction can introduce serious vulnerabilities.
The most important skill is learning to reason about application behavior: identify where input enters the system, understand how the application processes it, compare controlled responses, and distinguish reliable evidence from false positives.
For anyone learning web penetration testing, SQL injection is an important topic because it combines HTTP analysis, SQL fundamentals, application logic, and secure coding principles.








