SQL Injection (SQLi) – Complete Pentesting & Interview Guide

SQL Injection (SQLi) – Complete Pentesting & Interview Guide

SQL Injection (SQLi)

Complete pentesting and interview preparation guide — concepts, major types, identification, impact, remediation, testing workflow, and practice questions.

1. What is SQL Injection?

SQL Injection (SQLi) is a vulnerability that occurs when an application incorporates untrusted user input into an SQL query without safely separating data from SQL code.

An attacker may manipulate the query's intended logic. Depending on the database permissions and application design, this can lead to authentication bypass, unauthorized data access, data modification, or deletion.

Example: vulnerable query

SELECT * FROM users
WHERE username = 'admin'
AND password = 'admin123';

Vulnerable PHP pattern:

$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
Root cause: Unsafe construction of SQL statements, especially by concatenating untrusted input into query strings.

Potential impact

  • Authentication or authorization bypass.
  • Disclosure of sensitive database records.
  • Unauthorized modification or deletion of data.
  • Exposure of business or personal information.
  • In some configurations, further compromise through excessive database privileges.

2. Major SQL Injection categories

In-band SQLiResults are returned through the same channel.
Error-based and UNION-based
Inferential / Blind SQLiInformation is inferred from application behaviour.
Boolean-based and time-based
Out-of-band SQLiResults or signals are sent through a separate channel.
For example, DNS or HTTP callbacks

Other important patterns include second-order SQLi and stacked queries. Numeric-based, string-based, and authentication-bypass SQLi describe contexts or patterns rather than equivalent top-level categories.

3. In-band SQL Injection

In-band SQLi uses the same communication channel to submit input and observe results.

A. Error-based SQL Injection

Definition: The application exposes database error messages that reveal details about query execution or the database environment.

Why it happens

  • Verbose database errors shown to users.
  • Improper exception handling.
  • Untrusted input incorporated into dynamic SQL.

Illustrative test

Input: '

A vulnerable application might return a database syntax error, potentially revealing the database product or query context. An error alone is an indicator, not conclusive proof.

How to identify

  1. Identify parameters that may be used in database queries.
  2. Submit harmless unexpected characters in an authorized test.
  3. Compare normal and abnormal responses.
  4. Check whether database-specific errors are exposed.
  5. Reproduce and document the behaviour.

Impact

May disclose database type/version, query structure, table or column details, and—in some cases—sensitive records.

Remediation

  • Use parameterized queries.
  • Disable detailed database errors in production.
  • Log diagnostic details internally and return generic errors.
  • Use centralized exception handling.

B. UNION-based SQL Injection

Definition: The SQL UNION operator combines the result sets of two SELECT statements.

Illustrative SQL example

SELECT id, product FROM products
UNION
SELECT id, employee_name FROM employees;

For a UNION operation, the SELECT statements must return the same number of columns, and corresponding columns must have compatible data types.

How to identify

  • Determine whether input can influence a database query.
  • Observe errors or response changes when query structure is affected.
  • In a controlled lab, verify whether secondary query results are reflected in the response.

Impact and remediation

Potential impact includes unauthorized disclosure of database information. Remediate with parameterized queries, least-privilege database accounts, and safe error handling.

4. Inferential (Blind) SQL Injection

Blind SQLi occurs when the application does not directly display database errors or query results. A tester infers query behaviour from response differences or timing.

A. Boolean-based Blind SQL Injection

Definition: The tester compares application behaviour for conditions that evaluate to TRUE and FALSE.

Illustrative TRUE condition:  1 = 1
Illustrative FALSE condition: 1 = 2
ConditionPossible observation
TRUENormal result or one response pattern
FALSEDifferent content, status, or no record

Identification

  1. Establish a baseline response.
  2. Compare logically true and false test conditions in an authorized environment.
  3. Compare response body, status, and length.
  4. Repeat tests and rule out normal application variation.

Remediation

Use parameterized queries, enforce authorization server-side, validate expected input formats, and implement consistent error handling.

B. Time-based Blind SQL Injection

Definition: The tester observes whether a database operation causes a measurable delay, rather than relying on visible query output.

For example, some database engines provide delay functions such as MySQL's SLEEP(). A controlled lab can use a harmless delay to test whether a parameter influences query execution.

Identification

  1. Measure baseline response times.
  2. Compare requests with and without a controlled delay condition.
  3. Repeat measurements to account for network latency and server load.
  4. Correlate timing with the tested input.
Important: One slow response does not prove time-based SQLi. Use repeated, controlled comparisons and eliminate latency or load-related explanations.

Remediation

Use parameterized queries, restrict database permissions, monitor unusual query patterns, and apply appropriate query execution limits.

5. Out-of-band SQL Injection (OOB SQLi)

Definition: OOB SQLi occurs when a database interaction produces a signal or transfers data over a channel separate from the application's normal response—for example, a DNS or HTTP interaction.

Example scenario

  1. An application has an SQL Injection flaw.
  2. The database server has a feature capable of making an external network request.
  3. A controlled monitoring endpoint observes an unexpected DNS or HTTP callback.
  4. The tester correlates the callback with the test request.

How to identify

  • Use only a controlled callback domain or endpoint.
  • Monitor DNS/HTTP interactions.
  • Correlate timestamps and test inputs.
  • Check database outbound network access.

Impact

Potential information disclosure or data extraction, including where the application does not display query results.

Remediation

  • Use parameterized SQL queries.
  • Restrict outbound database network access.
  • Disable unnecessary database network functionality.
  • Apply least privilege and monitor outbound traffic.

6. Second-order SQL Injection

Definition: Second-order SQLi occurs when untrusted input is stored and later reused unsafely in another SQL query. The unsafe execution may happen in a later workflow, not when the input is first submitted.

Example scenario

  1. A user submits a profile field.
  2. The application stores the value in the database.
  3. Later, an administrative function retrieves that value.
  4. The retrieved value is concatenated into a new SQL statement without parameterization.

Why it happens

Developers may incorrectly assume that data already stored in their own database is trusted. Stored user input remains untrusted.

How to identify

  1. Map fields that persist user-controlled data.
  2. Trace where stored values are retrieved and reused.
  3. Test downstream workflows in an authorized environment.
  4. Review the relevant query construction and data flow.

Impact and remediation

Potential unauthorized data access or modification. Parameterize every query—including queries that use stored values—and validate data according to its intended use.

First-order SQLiSecond-order SQLi
Input is executed during the initial request.Input is stored and executed unsafely later.
Usually immediate.Delayed and workflow-dependent.
Often easier to reproduce.Requires tracing data flow across features.

7. Stacked Queries SQL Injection

Definition: Stacked queries occur when an input can cause multiple SQL statements to be processed in one database interaction. Whether this is possible depends on the database, driver, and application configuration.

SELECT * FROM users WHERE id = 10;
SELECT * FROM products;

How to identify

  • Understand the database engine and driver.
  • Review whether multiple statements are enabled.
  • Validate behaviour only in a controlled test environment.

Impact

Depending on permissions, additional statements could enable unauthorized data modification or deletion.

Remediation

  • Use parameterized queries.
  • Disable multi-statement execution when unnecessary.
  • Apply least-privilege database permissions.
  • Avoid dynamic SQL construction.

8. Other SQL Injection variations and contexts

VariationExplanation
Numeric-based SQLiInjection context is a numeric parameter, such as an ID.
String-based SQLiInjection context is a string parameter, such as a username or search term.
Authentication-bypass SQLiManipulation of login query logic may bypass authentication.
LIKE-based SQLiUnsafe construction of a SQL LIKE expression.
ORM-related SQLiUnsafe raw queries or dynamically constructed ORM expressions.
XML-derived SQLiXML-derived input is unsafely incorporated into an SQL query.
DNS-based SQLiAn out-of-band technique using DNS interactions.

These labels describe different input contexts, implementation patterns, or techniques. They are not all separate top-level SQLi categories.

9. Practical SQLi testing workflow

  1. Identify input parameters: URL parameters, request bodies, headers, cookies, search fields, login forms, and API parameters.
  2. Capture requests: Use Burp Suite to inspect requests and responses.
  3. Perform initial checks: Use harmless special-character and input variations in scope.
  4. Classify behaviour: Look for errors, reflected results, Boolean differences, timing differences, or controlled external callbacks.
  5. Validate: Reproduce the issue and eliminate false positives.
  6. Assess impact: Determine what data or operations are exposed, without exceeding authorization.
  7. Report: Include evidence, root cause, impact, severity, and remediation.
Reporting tip: A strong finding includes the affected endpoint and parameter, reproducible request/response evidence, the observed database behaviour, realistic impact, and a developer-ready fix.

10. Tools used for SQL Injection testing

ToolPurpose
Burp SuiteManual testing and HTTP request manipulation.
SQLmapAutomated detection and validation in authorized environments.
OWASP ZAPWeb application security testing and scanning.
Browser Developer ToolsInspect application requests and responses.
Database logsInvestigate query execution and errors.
PortSwigger Web Security AcademyPractice SQLi concepts in intentionally vulnerable labs.

11. How to prevent SQL Injection

1. Parameterized queries / prepared statements

Vulnerable PHP pattern:

$query = "SELECT * FROM users WHERE username = '$username'";

Safer PHP PDO example:

$stmt = $pdo->prepare(
    "SELECT * FROM users WHERE username = :username"
);

$stmt->execute([
    'username' => $username
]);

The query structure is defined separately from the supplied value. The database treats the username as data rather than SQL syntax.

2. Input validation

Validate according to expected format: IDs should be integers, quantities should be within valid ranges, and email fields should follow the application's requirements. Validation is useful but does not replace parameterized queries.

3. Least privilege

Give the application's database account only the permissions required for its tasks. A read-only feature should not have unnecessary UPDATE or DELETE permissions.

4. Secure error handling

Do not expose SQL statements, database credentials, stack traces, or internal database details to users. Log diagnostics securely on the server.

5. Avoid unsafe dynamic SQL

Do not concatenate untrusted values into SQL. For dynamic table or column identifiers—which usually cannot be bound as ordinary parameters—use strict allowlists.

12. Important SQL Injection interview questions

  1. What is SQL Injection?
  2. What is the root cause of SQL Injection?
  3. Explain the major types of SQL Injection.
  4. What is the difference between error-based and UNION-based SQLi?
  5. What is the difference between Boolean-based and time-based SQLi?
  6. What is out-of-band SQL Injection?
  7. What is second-order SQL Injection?
  8. What is the difference between first-order and second-order SQLi?
  9. What are stacked queries?
  10. What is the difference between UNION and UNION ALL?
  11. What is the difference between SQL Injection and NoSQL Injection?
  12. How do you test SQLi in REST APIs?
  13. How do you test SQLi in login functionality?
  14. Can SQL Injection happen through HTTP headers and cookies?
  15. Can SQL Injection occur in an application using an ORM?
  16. Does input validation completely prevent SQL Injection?
  17. How do prepared statements prevent SQL Injection?
  18. How would you report SQL Injection to a client?
  19. What is the business impact of SQL Injection?
  20. How would you test SQL Injection if database errors are disabled?

13. SQLi knowledge check

Choose an answer for each question, then submit to see your score and explanations.

Q1. An application displays a MySQL syntax error when you enter a single quote in a search parameter. Which type might this indicate?
Q2. An application returns different content for logically TRUE and FALSE conditions, but no database errors. Which type is this?
Q3. A username is stored today and triggers an unsafe SQL query when an administrator processes it later. What is this?
Q4. Which is the strongest primary defence against SQL Injection?
SQL Injection study guide • Use testing techniques only on systems you own or are explicitly authorized to assess.

Comments