What Is SQL Injection? Types, Examples, Prevention (Updated)

This SQL Injection guide was last updated in September 2021.

Code injections are the oldest known web application attack vectors, with successful hacks leading to a denial of service, loss of data integrity, data loss, and the compromise of entire networks. As a result, injection-based security vulnerabilities rank number one on the OWASP Top 10 Security Risks. They allow attackers to apply malicious code to information systems through user input interfaces. One such mechanism is a SQL Injection attack that involves the insertion of SQL queries to client input to access and manage backend databases. SQL Injection attacks are mostly carried out on web applications that rely on dynamic databases but lack sufficient input validation. 

This article delves into SQL Injection based security risks, various best practices, and useful SQL Injection tools to prevent such attacks.

A Deep Dive into SQL Injection Vulnerabilities

When a malicious user performs an SQL Injection (SQLi) attack, they typically intend to control the web application’s database server using malicious SQL statements. This allows them to bypass authentication controls required to access and retrieve the contents of the database. This usually is initiated by hackers scouting the application firewall for vulnerable user input points. Once identified, the attacker creates input content known as a malicious payload, executing unauthorized SQL injection commands at the back-end database. 

Attackers commonly develop SQL injection commands to perform a wide variety of malicious acts, such as:

  • Retrieving user credentials within the database
  • Selecting and outputting crucial system data
  • Appending or adding new data to a database
  • Deleting tables and records from the database
  • Using the back-end database server to access the Operating System

SQLi Security Assessment

Security Assessment SQL Injection


Types of SQL Injection Attacks

SQLi is a common and well-documented attack strategy whose success has far-reaching business consequences such as unauthorized viewing of credentials and gaining administrative access to the application’s database. SQLi attacks are categorized based on the following methods used to gain database access:

In-band SQLi

The attacker gathers their results using the communication channel they use to launch attacks. This code injection technique is common since it offers a simple, efficient way to access the database server. There are several types of in-band SQLi, including:

Error-based SQLi

The attacker relies on error messages relayed by the database server to learn about the database structure. Sometimes the error messages can provide sufficient data to enumerate the entire database.

Union-based SQLi

In this case, the malicious payload uses SQL’s UNION operator to combine the results of several SELECT statements to one output, which is returned along with the HTTP response. 

Blind SQL Injection/Inferential SQLi

In a Blind SQL injection technique, the hacker sends malicious data payloads, then reconstructs the database server’s structure using the web application’s response. In Blind SQLi, data is not retrieved by the web application, so the attacker cannot view the results of an attack using the same communication channel they used to launch this type of attack. Blind SQL Injection, also commonly referred to as the Inferential method, is of several types:

Content-based SQLi

Content/Boolean-based SQLi attacks force the web application to return different results depending on whether the malicious SQL query returns a TRUE or FALSE result. The query result determines whether the content in the HTTP response stays the same or changes. As a result, the attacker can determine whether the malicious payload returns a true or false result even though the query returns no data from the database.

Time-based SQLi

The attacker sends a query that forces the application to wait for a specific duration before returning a response. The attacker uses the response time to determine whether the result of a query is TRUE or FALSE. 

Out-of-Band SQLi

The attacker uses the same channel to launch the attack and gather results. While this attack is uncommon since it relies on certain database server features being enabled, it offers an alternative for orchestrating injection attacks if the server responses are unstable. 

SQL Injection Crashtest Security

How Attackers Perform SQLi

Web-page SQLi

When a web application asks for user input, some attackers supply SQL statements that are run unknowingly on the database. This section explores how attackers create payloads that generate valid SQL statements at the user input.

SQLi based on 1=1 is Always True

The attacker uses an OR statement to access all records in a table. When prompted for a User ID, the attacker inputs 105 OR 1=1. If the web application lacks sufficient input validation, this statement is accepted the generates a SQL command of the form:

SELECT * FROM Users WHERE UserId = 105 OR 1=1;

This query accesses and displays all records in the Users table since 1=1 is always TRUE.

SQLi based on “=” is Always True

Attackers use an OR statement to get combinations of related data. When prompted for a Username and Password, they key in ” or ” “=” on both fields. The database server then executes a command of the form:

SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

This command returns every row in the Users table since OR “=” is always true for Usernames and Passwords.

SQLi based on Batched Statements

Modern database servers accept batch statements, which hackers may exploit to target particular records or tables. For instance, when prompted for their User ID, they input 105; DROP TABLE Suppliers. This executes a valid statement of the form:

SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;

This deletes the table Suppliers from User records.

Commonly Known SQLi Attack Examples & Technique

Successful SQLi attacks can tamper with existing data, disclose crucial information, gain administrative rights to networks and cause repudiation issues. Examples of SQLi attacks on enterprise systems include:

The 2019 Bulgarian National Revenue Agency Data Breach

On 15th July 2019, an anonymous hacker announced that they had successfully deployed an SQL injection on the national tax authority’s servers. The hacker extracted 11 GB of data in 57 folders of .csv files that contained the names and identification information of over 6 million people. The files also included citizens’ social security payments, taxes, online betting data, debts, company activities, and revenues collected for over 12 years.

The 2020/2021 Accellion Data Breach

Attackers used an SQL injection vulnerability to gain initial access to the Accellion File Transfer Appliance (FTA). They caused a massive data breach affecting multiple companies in different sectors and countries. The victims’ data began to appear on CLOP LEAKS, a ransomware forum. The zero-day vulnerabilities that enabled a successful attack are yet to be fixed as more companies keep reporting compromises of user data.

How to Prevent SQL injection Attacks

Preventing SQLi attacks is a complex and rigorous process since prevention techniques vary according to the programming language used, the SQL database engine, and the SQLi subtype. This section explores the tools and best practices to prevent SQL Injection vulnerabilities.

SQL Injection prevention guide

Prevention Guide

SQLi prevention guide

Learn how to detect and prevent one of the most prevalent vulnerabilities – SQL injection. Download this guide for free.


Best Practices to Prevent SQLi Vulnerabilities

Some strategic principles and practices to keep web applications safe from SQLi attacks include:

Regular Scanning

Attackers inject malicious input through vulnerabilities they discover in the system code. Therefore, security teams should undertake a SQL injection scanner. Using the right tools is relevant to find any possible SQLi vulnerabilities before attackers can take advantage of them.

Training & Awareness

Everyone involved in developing and managing the application should understand the risk and impacts of SQL injections. Training should also be extended to users to understand why it is important only to include valid inputs when prompted.

Filter User Input

A database administrator should never trust user input. Internal and public user inputs should all be filtered and validated before being exposed to the database server.

Use Whitelist-based Filters

Attackers will always develop clever methods to circumvent blacklists. Whitelisting prevents attacks using a list that only allows certain users to access the protected system. In addition, malicious payloads deployed by SQLi injections cannot execute when they don’t exist in the whitelist.

Use Updated Web Technologies

Software updates often include patches for discovered vulnerabilities. Hackers typically rely on these vulnerabilities to deploy malicious payloads. Using the latest patched versions of development environments and frameworks will meet compliance standards and keep the web application safe from exploits as most software organizations try to stay ahead of hackers. 

SQL Injection Practical Prevention Tips

To prevent SQL injection attacks, treat all user input as potentially malicious and follow some programming guidelines:

Filter User Input

For an attacker to successfully execute an SQL injection, he needs to plant some code run by the web application’s database. Therefore all user input should be validated first and limited to the needed characters. E.g., you may ask a user to input a username, password, and e-mail address in a registration form. You can limit the allowed characters of these input fields to characters that do not interfere with the database. The following example filters out user input for the three values in PHP:

if (preg_match("/[^A-Za-z0-9]/", $username) ||
  (preg_match("/[^A-Za-z0-9\!_-]/", $password) ||
  (preg_match("/[^A-Za-z0-9_-@]/", $email)) {
    echo "Invalid Characters!";
} else {
    # Run Database Command

Database Mappers

Most modern web frameworks provide some abstraction of database handling. E.g., Laravel provides Eloquent queries. Created objects are automatically converted and stored or retrieved from the database. In the example of the user registration form, one could create the user object in the following way:

$user = new User;
$user->username = $request->username;
$user->password = $request->password;
$user->email = $request->email;

The resulting SQL statement is automatically sanitized and will prevent SQL injections.

Sanitize User Input / Prepared Statements

It may not always be possible to use a database mapper. In these cases, use prepared statements to create your SQL queries. These statements validate and sanitize the user-provided values and prevent SQL injections. E.g., in PHP, you can create a prepared statement the following way:

$stmt = $mysqli->prepare("INSERT INTO users(username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $password, $email) # "sss" here states, that three strings are expected.
$username = $request->username;
$password = $request->password;
$email = $request->email;

Tools to Prevent, Detect and Remediate SQLi Vulnerabilities

Regular SQL vulnerability assessment scan is the first actionable remediation to keeping web applications safe from SQLi vulnerabilities. Here is a list of popular vulnerability scanners that can help security teams identify and resolve SQLi vulnerabilities:

Crashtest Security

Crashtest Security is an end-to-end security testing suite that simplifies vulnerability scanning through quick security assessments, risk reduction, and rich vulnerability reports. In addition, Crashtest integrates with multiple layers of the development stack, allowing teams to establish a continuous testing process and eliminate attack surfaces on APIs and web applications.

The security platform also automates vulnerability scanning and seamlessly delivers security information on the web application, allowing development teams to focus on clean code. 


A complete security testing solution can be used for distributed and standalone systems. Acunetix integrates seamlessly with market-leading development frameworks and comes with in-built vulnerability scanning and management functions. Acunetix also interfaces with third-party issue trackers to help with end-to-end vulnerability management.

Burp Suite

A Web Application Security Testing solution developed by PortSwigger to help organizations fight zero-day threats through automated scanning. The suite also includes penetration testing functions that can be used to identify the impact of SQLi attacks on web servers. The suite comes in an Enterprise and Professional Edition that offers different vulnerability management tools for web application security. 

Imperva Database Security

Imperva is a database risk & compliance management platform that delivers analytics, response, and protection for organizational data assets. The platform integrates with any database so organizations can use its global preconfigured reports, policies, and templates as soon as Imperva is deployed. 

Videos About SQL Injections

Video about SQL injection types
Video about SQL injection prevention


Despite extensive efforts to remediate issues, SQLi vulnerabilities are still popular. It is estimated that 8% of websites and web applications have at least one vulnerability. In addition, attackers leverage SQLi vulnerabilities in many ways to compromise a web application through unauthorized database access. 

To help with this, the Crashtest Security Suite helps organizations protect their web applications and APIs from injection attacks through continuous vulnerability scans and testing. In addition, the security platform fits seamlessly in the DevOps toolchain, enabling organizations to develop and deploy safer javascript, web applications, and APIs.

Sign up for free here to know how Crashtest Security can help with a rapid vulnerability assessment scan to achieve a robust security model. 

Get a quick security report for your website for free now

We are analyzing
Scanning target
Scan status: In progress
Scan target:
Date: 30/11/2023
Crashtest Security Suite will be checking for:
Information disclosure Known vulnerabilities SSL misconfiguration Open ports
Complete your scan request
Please fill in your details receive the
quick security audit by email.
Security specialist is analyzing your scan report.
То verify your identity please provide your phone/mobile:
Thank you.
We have received your request.
As soon as your security audit is ready, we will notify you.