
SQL injection is one of the oldest and most dangerous web attacks, and it still features in the OWASP Top 10. An attacker can read, change or even delete a website's database simply by typing malicious input into a login form, search box or URL. If you are learning web security through a cyber security course in Dehradun, SQL injection is one of the first vulnerabilities you will learn to find and fix.
In this guide, we explain what SQL injection is in simple words, how a SQL injection attack works, the main types of SQL injection with examples, and the best ways to prevent it.
What is SQL Injection?
SQL injection (SQLi) is a web security vulnerability where an attacker inserts (or "injects") their own SQL code into a query that an application sends to its database. When the application builds a query by directly joining user input into SQL text, the database cannot tell the difference between the developer's code and the attacker's input, so it runs both.
SQL (Structured Query Language) is the language websites use to talk to databases such as MySQL, PostgreSQL, Oracle and Microsoft SQL Server. Login pages, product searches, contact forms and dashboards all run SQL queries in the background. Any place where user input reaches one of these queries without proper handling can become an entry point for SQL injection.
How Does a SQL Injection Attack Work?
Let's take a simple login form. Behind the scenes, a poorly written application might build a query like this:
SELECT * FROM users WHERE username = 'input_username' AND password = 'input_password';The application simply pastes whatever the user types into the query. A normal user types their username and password, and the query works as expected.
Now imagine an attacker types this into the username field:
' OR '1'='1' --The final query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' --' AND password = '';Here is what happens:
The single quote (
') closes the username value early.OR '1'='1'adds a condition that is always true.--turns the rest of the query, including the password check, into a comment.
The database returns user records without checking the password, and the attacker may be logged in, often as the first user in the table, which is frequently the admin. This classic example shows the core problem: user input is being treated as code instead of data.
Why is SQL Injection Dangerous?
A successful SQL injection attack can lead to:
Data theft: usernames, passwords, emails, phone numbers and payment details can be exposed.
Authentication bypass: attackers log in without valid credentials.
Data tampering: records can be modified, such as changing prices or account balances.
Data deletion: entire tables can be dropped, causing downtime and loss.
Full server compromise: in badly configured systems, attackers can run commands on the database server itself.
Legal and reputation damage: data breaches can attract penalties under data protection laws such as India's DPDP Act, and loss of customer trust.
Types of SQL Injection
SQL injection attacks are usually grouped into three main categories: in-band, blind (inferential) and out-of-band. Here is a quick overview:
Type | Sub-type | How it works |
|---|---|---|
In-band SQLi | Error-based | Uses database error messages shown on the page to learn about the database structure. |
Union-based | Uses the UNION operator to combine the attacker's query results with the original results on the same page. | |
Blind (Inferential) SQLi | Boolean-based | Sends true/false conditions and watches how the page changes to infer data. |
Time-based | Makes the database pause (delay) when a condition is true, and measures response time. | |
Out-of-band SQLi | - | Makes the database send data to an external server the attacker controls, for example through DNS or HTTP requests. |
1. In-Band SQL Injection
In-band SQL injection is the most common and easiest type. The attacker uses the same channel to launch the attack and collect the results, usually the web page itself.
Error-based SQL injection: the attacker deliberately causes database errors. If the application displays detailed error messages, they reveal table names, column names or the database version.
Union-based SQL injection: the attacker uses the
UNION SELECTstatement to attach extra data, such as usernames and password hashes, to the normal output of a page like a product list.
2. Blind SQL Injection
In blind SQL injection, the application does not show query results or errors directly. The attacker asks the database a series of yes/no questions and reads the answers from the application's behaviour.
Boolean-based blind SQL injection: the page looks different when a condition is true versus false, for example a product showing or not showing.
Time-based blind SQL injection: the attacker uses functions like
SLEEP()so that the page loads slowly when a condition is true. The delay itself is the answer.
Blind attacks are slower, but they are just as dangerous, because data can still be extracted one character at a time, usually with automated tools.
3. Out-of-Band SQL Injection
Out-of-band SQL injection is less common. It is used when the attacker cannot see results on the same channel and the server responses are unreliable. The injected query makes the database send data to an external system, for example by triggering a DNS lookup to a domain the attacker controls. It depends on specific database features being enabled.
SQL Injection Examples in Real Life
SQL injection is not just a textbook topic. Over the years, it has been behind many large data breaches affecting retailers, payment processors, telecom companies and government websites, exposing millions of user records. Many of these incidents happened because a single input field, often a forgotten old page or a search parameter in a URL, was passed straight into a database query.
Common places where SQL injection is found include:
Login and registration forms
Search boxes and filters
URL parameters such as
product.php?id=10Cookies and HTTP headers
API endpoints that accept JSON or form data
SQL injection is one of many web attacks security teams defend against. You can read about others in our guide to the different types of cyber attacks.
How to Prevent SQL Injection
The good news is that SQL injection is highly preventable. These are the most effective defences, starting with the most important:
1. Use Parameterized Queries (Prepared Statements)
This is the number one defence. With parameterized queries, the SQL code and the user input are sent to the database separately. The database always treats the input as data, never as code, no matter what characters it contains.
Example in Python:
cursor.execute(
"SELECT * FROM users WHERE username = %s AND password_hash = %s",
(username, password_hash)
)Example in PHP (PDO):
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);Even if a user types ' OR '1'='1, it is simply searched as a literal text value and the attack fails.
2. Use Stored Procedures and ORMs Safely
Stored procedures and ORM frameworks (like Django ORM, Hibernate, Sequelize or Laravel Eloquent) usually build safe, parameterized queries for you. But they can still be vulnerable if developers build raw SQL strings inside them, so avoid string concatenation everywhere.
3. Validate and Sanitize Input
Use allow-list validation: accept only what you expect. For example, an ID field should accept only numbers, a date field only valid dates, and a sort option only a fixed list of column names. Input validation is a strong extra layer, but it should support parameterized queries, not replace them.
4. Apply the Principle of Least Privilege
The database account used by your web application should have only the permissions it needs. A website that only reads product data should not connect with an admin account that can drop tables or access other databases. This limits the damage if an injection does happen.
5. Hide Detailed Error Messages
Never show raw database errors to users. Display a generic error message and log the technical details privately. This takes away the information attackers rely on for error-based SQL injection.
6. Use a Web Application Firewall (WAF)
A WAF can detect and block common SQL injection patterns before they reach your application. It is a useful safety net, especially for older applications, but it can be bypassed, so it is not a substitute for secure code.
7. Test Regularly
Include SQL injection checks in code reviews and in regular security testing. Authorised security testers use tools such as Burp Suite and sqlmap to find injectable parameters before attackers do. Automated scanners plus manual testing give the best coverage.
SQL Injection vs XSS: What's the Difference?
Point | SQL Injection | Cross-Site Scripting (XSS) |
|---|---|---|
Target | The database on the server | Users' browsers |
Injected code | SQL queries | JavaScript / HTML |
Main impact | Data theft, data changes, login bypass | Session hijacking, defacement, phishing |
Main defence | Parameterized queries | Output encoding and Content Security Policy |
Skills You Need to Find and Fix SQL Injection
If you want to work in web application security, penetration testing or a SOC team, understanding SQL injection is essential. The key skills include:
Basic SQL and how databases work
How web applications handle requests and responses (HTTP)
Secure coding in at least one language, such as Python, PHP or Java
Tools like Burp Suite, sqlmap and Kali Linux
Knowledge of the OWASP Top 10 and ethical hacking methods
Important: only test for SQL injection on systems you own or have written permission to test. Practise on legal lab environments such as DVWA, PortSwigger Web Security Academy or your training institute's labs. Testing other websites without permission is illegal.
Conclusion
SQL injection happens when an application treats user input as part of a database command. It can expose sensitive data, bypass logins and even take over servers, but it is almost entirely preventable with parameterized queries, input validation, least-privilege database accounts and regular security testing.
Want hands-on practice with SQL injection, Burp Suite and real-world security labs? Join Brillica Services' Advanced Cyber Security with AI program at our Dehradun branch, or enrol in our cyber security course in Delhi at the Tagore Garden branch.
Frequently Asked Questions
What is SQL injection in simple words?
SQL injection is an attack where a hacker types malicious SQL code into a website's input field, such as a login form, so that the website's database runs the attacker's commands. This can expose, change or delete data.
What are the main types of SQL injection?
The three main types are in-band SQL injection (error-based and union-based), blind SQL injection (boolean-based and time-based) and out-of-band SQL injection.
How do you prevent SQL injection?
The best defence is using parameterized queries (prepared statements). Add input validation, least-privilege database accounts, hidden error messages, a web application firewall and regular security testing.
Is SQL injection still common today?
Yes. Injection flaws, including SQL injection, are still part of the OWASP Top 10, mainly because of old code, rushed development and raw SQL queries built from user input.
Which tools are used to detect SQL injection?
Security professionals commonly use Burp Suite, sqlmap and OWASP ZAP to detect SQL injection, but only on systems they own or are authorised to test.
What is the difference between SQL injection and XSS?
SQL injection targets the database on the server using SQL code, while cross-site scripting (XSS) injects JavaScript that runs in other users' browsers.
