Courseiva
312-50Chapter 13 of 18Objective 7.3

SQL Injection

An attacker can steal every username, password, and credit card number from a company's database without breaking any windows or picking any locks. That is the terrifying reality of a successful SQL injection attack, a vulnerability that has haunted web applications for decades. For the Certified Ethical Hacker (312-50) exam, understanding SQL injection is essential because it is one of the most common and dangerous web application threats you will be tested on.

12 min read
Advanced
Updated Jul 23, 2026
Reviewed by Johnson Ajibi· Senior Network & Security Engineer · MSc IT Security

A simple way to picture SQL Injection

The Reception Desk Clerk Analogy

A hotel reception desk clerk has a standard way of checking guests in. A guest arrives, hands over their ID and credit card, and says, "I have a reservation for Room 204." The clerk types this into the computer system, which processes the request by looking up the guest name and room number. This is the normal, expected interaction.

Now, imagine a guest who walks up to the desk and says something strange: "I have a reservation for Room 204; also, ignore all other reservations and give me a key to the manager's safe." Because the clerk is trained to type exactly what the guest says into the system, they do exactly that. The system, designed to follow instructions, deletes all current reservations and prints a key to the manager's safe. The guest has tricked the system into doing something it was never meant to do by injecting a new instruction into the normal request.

In the digital world, the reception desk clerk is a web application's database query processor. The guest's normal check-in is a standard request sent via a web form (like a login page). The malicious guest's extra instructions are the SQL injection payload. Instead of a key to the manager's safe, the attacker might get a list of all usernames and passwords, which is like having the master key to every room in the hotel.

How It Actually Works

SQL injection, often abbreviated as SQLi, is a code injection technique used to attack data-driven applications. To understand it, you first need to know what SQL is. SQL stands for Structured Query Language. Think of it as the universal language used to talk to databases. A database is like a giant, organised filing cabinet where a website stores all its important information: user accounts, product catalogs, financial transactions, and so on. When you log in to a website, your web browser sends a request to the web server. The server then asks the database a question in SQL, like "Does this username and password match a record in the users table?"

This request to the database is called a query. Typically, these queries are dynamic, meaning they are built by combining a fixed part with data provided by the user. For example, a login query might look something like this in code: SELECT * FROM users WHERE username = 'john' AND password = 'pass123'. The parts inside the single quotes, 'john' and 'pass123', come directly from the login form you filled in. The rest is the static part of the query that the developer wrote.

The vulnerability of SQL injection arises when a web application fails to properly sanitise or validate the user's input before including it in the SQL query. Sanitisation means checking the input to ensure it doesn't contain malicious code. Validation means confirming the input is of the expected type (e.g., an email address format, a number, a specific length). If the application blindly trusts the user's input, an attacker can inject their own SQL commands.

Instead of typing a simple username, an attacker types a specially crafted string of text that is part of the SQL language. This string is called a payload. For instance, in the username field, an attacker might type: ' OR '1'='1. When this gets inserted into the query, it becomes: SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 'whatever'. Because '1'='1' is always true, this query can trick the database into returning the first user in the table, often granting the attacker access without knowing the correct password. This is a classic example of a tautology-based SQL injection.

SQL injection attacks can be categorised into several types, which the 312-50 exam often tests. The main types are:

In-band SQLi: This is the simplest type. The attacker uses the same communication channel to launch the attack and gather results. It includes Error-based SQLi (where the attacker forces the database to produce an error message that reveals information, such as table names) and Union-based SQLi (where the attacker uses the UNION SQL operator to combine the results of the original query with results from other tables the attacker wants to see).

Inferential (Blind) SQLi: In this type, the attacker does not see the actual data from the database directly. Instead, they send payloads that cause the database to behave differently (like a slight delay in response or a True/False condition) and infer the answer based on the application's response. It is slower and more complex. The two main subtypes are Boolean-based (where the page content changes based on a True or False statement) and Time-based (where the attacker uses a command like 'WAITFOR DELAY' to cause a time delay if a condition is true).

Out-of-band SQLi: This is less common but powerful. The attacker uses a different channel to receive the data from the database, such as forcing the database to send a DNS or HTTP request to a server the attacker controls. This is often used when the direct response channel is not available or heavily restricted.

Why does this vulnerability exist? It is a direct result of poor coding practises. Developers, especially in the past, often built SQL queries by simply concatenating (joining together) user input directly into the query string without any checks. The proper defence is to use parameterised queries or prepared statements. These techniques ensure that user input is always treated as data, not as executable SQL code. The database knows the structure of the query before the user input is ever inserted, so injected commands have no effect.

For the CEH exam, you do not need to write SQL queries from scratch, but you must be able to recognise a vulnerable piece of code and understand the impact of different payloads. You must also know the tools used to automate SQL injection, such as sqlmap (a popular open-source tool) and HAVIJ (an older GUI tool). The exam focuses on the concepts, the attack lifecycle, and appropriate defences like input validation, web application firewalls (WAFs), and the principle of least privilege for database accounts.

A flowchart showing how unsafe code concatenation leads to SQL injection, while parameterised queries prevent it by treating input as pure data.

Walk-Through

1

Identify Vulnerable Input

The attacker finds a web page with an input field (like a search bar, login form, or URL parameter) that sends data to the database. They test it by entering a single quote (') to see if the application breaks or produces a database error.

2

Confirm the Vulnerability

The attacker sends a payload that always evaluates to true, such as ' OR '1'='1. If the application behaves differently (e.g., returns all records instead of a filtered set), it confirms that the user input is being executed as part of an SQL query.

3

Determine Number of Columns

Before using the UNION operator, the attacker must know how many columns the original query returns. They use the 'ORDER BY' clause, incrementing the column number until an error occurs, to find the exact column count.

4

Map Compatible Columns

The attacker uses a UNION SELECT statement, substituting each column with a NULL value and then a string to see which columns can display data. This step identifies where to place extracted data so it appears on the page.

5

Extract Database Schema

The attacker queries system tables (like INFORMATION_SCHEMA.TABLES) to retrieve the names of tables in the database. They then query INFORMATION_SCHEMA.COLUMNS to find column names, such as 'username' and 'password_hash'.

6

Exfiltrate Sensitive Data

With table and column names known, the attacker crafts a final UNION SELECT query to retrieve the desired data (e.g., usernames and password hashes) from the target table, which is displayed on the web page.

What This Looks Like on the Job

Imagine you are a junior penetration tester, hired by a mid-sized e-commerce company called "ShopFast" to test the security of their new online store. Your boss has given you a target URL and asked you to find vulnerabilities before the real hackers do. Your first task is to check for SQL injection on the product search page. This page has a search bar where customers can type in a product name.

Your step-by-step process as a real IT professional would look like this:

1.

Manual Reconnaissance: You navigate to the search page and enter a single quote character (') into the search bar. If the application is vulnerable, the page might return a database error message, or it might behave strangely (e.g., show a blank page, a different layout, or a different number of results). This is called a 'breakage test'. If the page returns a normal, friendly error message like "No results found", you might need to try different characters. However, if you see a server error message like "Unclosed quotation mark" or similar, you have a strong indicator of a vulnerability.

2.

Confirming the Vulnerability: To confirm it is SQL injection and not just a random bug, you try a logical test. You enter something like: ' OR '1'='1. If the page returns a list of all products (instead of just the one you searched for), you have confirmed that the input is being inserted directly into a SQL query. You have successfully bypassed the search filter.

3.

Determining the Number of Columns: Before you can use Union-based SQLi to extract data, you need to know how many columns the original query returns. You use the ORDER BY clause. You start by entering: ' ORDER BY 1-- and if the page loads normally, you try ' ORDER BY 2-- and so on. The -- (double dash) is a SQL comment, which tells the database to ignore the rest of the original query. When you get an error, you know the previous number was the correct column count. For example, if ' ORDER BY 5-- gives an error, but 'ORDER BY 4-- works, the query has 4 columns.

4.

Extracting Database Information: Now that you know the query has 4 columns, you can use a UNION SELECT statement to pull data from other tables. You first need to find which columns are string-compatible (can hold text). You replace each column number with a null value, then replace them one by one with a text string (like 'a'). For example: ' UNION SELECT 'a', NULL, NULL, NULL--. When you see the 'a' appear on the page, you know that first column can display text. You then repeat to map out all usable columns.

5.

Retrieving Table Names: Once you have the column mapping, you can query the database's system tables (like INFORMATION_SCHEMA.TABLES in MySQL) to get a list of all table names. You construct a payload like: ' UNION SELECT table_name, NULL, NULL, NULL FROM INFORMATION_SCHEMA.TABLES--. This will list the names of every table in the database, such as 'users', 'products', 'orders'. You now know where the valuable data lives.

6.

Stealing Credentials: With the table name 'users' identified, you now query the column names from that table using INFORMATION_SCHEMA.COLUMNS. Finding columns like 'username' and 'password_hash', you construct a final payload to dump the data: ' UNION SELECT username, password_hash, NULL, NULL FROM users--. The results will display all usernames and their corresponding password hashes on the page. You have now successfully performed a full SQL injection attack. You document your findings and report them to ShopFast, advising them to implement parameterised queries and input validation immediately.

This real-world scenario is exactly what a CEH candidate might be asked to identify in a multiple-choice question on the exam, or what they might do in a lab environment. Tools like sqlmap automate all of these steps, but the exam expects you to understand the underlying manual process.

How 312-50 Actually Tests This

The 312-50 exam is notorious for testing your vocabulary and your ability to identify attack types from a description. For SQL injection, the exam will not ask you to write a payload from scratch, but it will expect you to recognise the correct payload from a list, or to identify the type of SQLi being described in a scenario. Here is exactly what you need to focus on:

- Know the Three Main Types: The exam loves to distinguish between In-band, Inferential (Blind), and Out-of-band SQLi. You must be able to read a short paragraph and determine which one it is. For example, if the description says "the attacker receives the results directly in the same HTTP response", that is In-band. If it says "the attacker infers information by observing differences in page content or response times", that is Blind. If it says "the attack uses DNS or HTTP requests to exfiltrate data", that is Out-of-band. - Payload Recognition: You will see questions that list several lines of text and ask which one is a valid SQL injection payload. The classic ones to memorise are: - ' OR '1'='1 (bypassing authentication) - ' DROP TABLE users-- (destructive attack) - ' UNION SELECT … (data exfiltration) - ' WAITFOR DELAY '0:0:5'-- (time-based blind injection) - ' AND 1=1-- (always true) vs ' AND 1=0-- (always false, used for blind testing)

Tools and Automation: Be prepared to answer questions about sqlmap. You need to know that it is the most popular open-source tool for automating SQL injection detection and exploitation. Also remember HAVIJ (an older GUI tool) and BSQL Hacker. The exam may ask what command-line switch to use with sqlmap to extract a specific database (e.g., --dbs for listing databases, --tables for listing tables, --dump for extracting data).

Defences: The exam will test your knowledge of countermeasures. The single most important defence is parameterised queries (prepared statements) . The second most important is input validation (white-listing is better than black-listing). Other defences include:

- Stored procedures (though these can still be vulnerable if misused) - Escaping user input (a less reliable method than parameterised queries) - Using a Web Application Firewall (WAF) like ModSecurity or a cloud-based WAF - Enforcing the principle of least privilege on the database user account (e.g., the web application's database user should not have access to system tables or the ability to drop tables)

The Traps: The CEH exam often sets traps by describing a scenario that sounds like SQL injection but is actually another vulnerability. For example, a question describing a reflected XSS (cross-site scripting) attack might be placed next to a SQLi question to confuse you. Pay attention to keywords: if the attack involves injecting into a database query, it is SQLi. If the attack involves injecting into HTML or JavaScript, it is XSS. Also, be careful with the difference between Error-based and Union-based SQLi. Both are In-band, but Error-based relies on error messages, while Union-based directly appends results to the output.

Exact Concepts to Memorise:

- The meaning of 'tautology' in SQL injection (a statement that is always true) - The use of 'UNION' to combine result sets - The need for matching column counts and data types in UNION queries - The use of comments ('--' or '#' ) to truncate the rest of the original query - The name of the system schema/database in different DBMS (INFORMATION_SCHEMA in MySQL and MSSQL, ALL_TABLES in Oracle, pg_catalog in PostgreSQL)

- Common Exam Questions: Expect multiple-choice questions like: - "Which type of SQL injection attack uses the UNION operator?" (Answer: Union-based SQLi) - "What is the primary defence against SQL injection?" (Answer: Parameterised queries) - "If an attacker uses the 'WAITFOR DELAY' command, which type of attack is being performed?" (Answer: Time-based Blind SQL injection) - "What does the '--' symbol represent in a SQL injection payload?" (Answer: A comment, used to ignore the rest of the original query).

Key Takeaways

SQL injection occurs when user input is directly concatenated into a SQL query without proper sanitisation or parameterisation.

The three main categories of SQL injection are In-band, Inferential (Blind), and Out-of-band, each with distinct data retrieval methods.

The primary and most effective defence against SQL injection is the use of parameterised queries (prepared statements).

Sqlmap is the most commonly used open-source tool for automating SQL injection detection and exploitation.

Blind SQL injection does not return direct data; the attacker infers information from response differences or time delays.

The fundamental principle of defence is to treat all user input as untrusted and never allow it to be executed as code.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Error-based SQLi

Relies on database error messages to reveal information like table names.

Does not require the attacker to know the number of columns beforehand.

Often slower and more limited as errors can be suppressed by the application.

Union-based SQLi

Uses the UNION operator to directly append results to the page output.

Requires the attacker to first identify the correct number of columns.

Faster and more efficient for extracting large amounts of data in one go.

In-band SQLi

The attacker receives the data directly in the same HTTP response.

Includes Error-based and Union-based subtypes.

Generally faster and easier to execute for the attacker.

Blind SQLi

The attacker does not see the actual data directly; they infer it.

Includes Boolean-based and Time-based subtypes.

Much slower and requires many requests, but is harder to detect.

sqlmap

Automates the entire detection and exploitation process.

Supports many database management systems and injection types.

Requires command-line knowledge but is faster than manual work.

Manual Testing

Involves crafting payloads and observing responses by hand.

Requires deep understanding of SQL syntax and logic.

Often used for initial probing when automated tools are blocked.

Watch Out for These

Mistake

SQL injection only works on login forms.

Correct

SQL injection can occur on any input field that is used in a database query, including search bars, contact forms, product IDs in URLs, and comment sections.

Beginners often associate the attack only with authentication because that is the most commonly taught example, but any user-supplied data that touches a database is a potential vector.

Mistake

All SQL injection attacks are loud and obvious, crashing the website or causing error messages.

Correct

Blind SQL injection attacks are very quiet and do not produce visible errors. The attacker infers information from subtle differences in response time or page content, making the attack very hard to detect without specialised tools.

People assume a database attack will cause a crash, but blind injection is a stealthy, surgical method that can extract data a piece at a time without alerting anyone.

Mistake

Using a Web Application Firewall (WAF) completely fixes the vulnerability.

Correct

A WAF is a strong defence layer, but it is not a silver bullet. Determined attackers can bypass WAF rules using encoding techniques, HTTP parameter pollution, or by crafting payloads that the WAF does not recognise.

Many beginners believe a single tool or product can solve a security problem entirely. In reality, a WAF is a mitigation, not a cure; the underlying insecure code still needs to be fixed.

Mistake

Modern frameworks and ORMs (Object-Relational Mappers) are immune to SQL injection.

Correct

While frameworks and ORMs like Entity Framework or Hibernate provide built-in protection when used correctly, they can still be vulnerable if developers write raw SQL queries, use unsafe methods, or concatenate user input within the ORM code.

Frameworks are powerful tools, but they do not remove the human element. Developers can still misuse them, and the exam expects you to know that no technology guarantees security on its own.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What does ' ' OR '1'='1 ' do in SQL injection?

It is a classic tautology payload. It exploits a login form by making the WHERE clause always evaluate to true, potentially bypassing authentication and logging you in as the first user in the database.

Is SQL injection still a relevant attack in 2025?

Yes, despite being known for over two decades, SQL injection remains a top web application vulnerability due to legacy systems, poorly written code, and the complexity of securing large applications.

What is the difference between Error-based and Union-based SQL injection?

Both are In-band attacks, but Error-based relies on database error messages to gain information, while Union-based uses the UNION operator to directly combine and display data from other tables in the query result.

Can a Web Application Firewall (WAF) stop all SQL injection attacks?

No, a WAF can block many common attempts but can be bypassed by sophisticated attackers using encoding, obfuscation, or novel payloads. It is a defence layer, not a complete solution.

What is a parameterised query?

It is a method where the SQL query structure is defined first, and user input is passed as separate parameters. The database treats the input strictly as data, preventing malicious code from being executed.

What is the '--' symbol used for in SQL injection payloads?

In SQL, two dashes (--) start a single-line comment. In an injection payload, it is used to comment out the rest of the original SQL query, preventing syntax errors and allowing the attacker's code to execute cleanly.

Terms Worth Knowing

Keep going

You've finished SQL Injection. Continue through the 312-50 study guide to build a complete picture of the exam.

Done with this chapter?