Skip to content
Back to Blog
·9 min read·technology

SQL Injection Explained: How It Works and How to Prevent It

SQL injection lets attackers manipulate your database through user inputs. Learn how in-band, blind, and union-based attacks work — and how to prevent them.

BR

Bachao.AI Research Team

Cybersecurity Research

Scan Your Stack for This

Security exposure this creates

Unpatched vulnerabilities in your tech stack are the #1 entry point for breaches targeting Indian businesses. Here's what to watch.

SQL injection (SQLi) is a cyberattack technique where an attacker inserts malicious SQL code into an input field, tricking the database into executing unintended commands. It remains the most documented web vulnerability and consistently appears in the OWASP Top 10 — not because developers don't know about it, but because it keeps getting overlooked in fast-moving Indian development teams shipping under deadline pressure. The good news: it is almost entirely preventable with parameterized queries and disciplined input handling.

#3Injection ranked in OWASP Top 10 in every edition since 2003 (OWASP 2021)
73%of Indian SMBs have never conducted a security audit (DSCI 2024)

What Is SQL Injection

When your application builds a database query by directly concatenating user input, you hand the attacker a keyboard wired to your database. Consider a simple login check in PHP:

php
// Vulnerable
$query = "SELECT * FROM users WHERE email='" . $_POST['email'] . "' AND password='" . $_POST['password'] . "'";

An attacker enters ' OR '1'='1 as the email. The query becomes:

sql
SELECT * FROM users WHERE email='' OR '1'='1' AND password=''

Because '1'='1' is always true, the query returns the first row — usually an admin account. The attacker is now logged in without a valid password.

This is authentication bypass, one of several attack classes that SQLi enables.

How SQL Injection Attacks Work — The Full Flow

graph TD A[Attacker identifies input field] --> B[Injects SQL payload into input] B --> C{Application builds query by string concat} C --> D[Malicious SQL reaches DB engine] D --> E{Attack type} E --> F[In-Band Error-Based]:::danger E --> G[In-Band Union-Based]:::danger E --> H[Blind Boolean-Based]:::danger E --> I[Blind Time-Based]:::danger F --> J[Full schema extracted]:::danger G --> J H --> J I --> J J --> K[Tables listed, rows dumped]:::danger K --> L[Credentials, PII, financial data exfiltrated]:::danger classDef danger fill:#5f1e1e,stroke:#EF4444,color:#e2e8f0

The Four Main SQLi Techniques

In-Band — Error-Based

The attacker forces the database to produce an error message containing sensitive information. MySQL, for example, will sometimes return table names and column values inside error text. A single payload like ' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version()))) -- can reveal the database version, which narrows down which known CVEs to exploit next.

In-Band — Union-Based

The UNION SQL operator combines the results of two SELECT statements. If the attacker can guess the number of columns and their data types, they can append a second query that pulls from any table:

sql
' UNION SELECT username, password, NULL FROM admin_users --

The result set gets returned to the page as if it were normal application data.

Blind — Boolean-Based

When the application returns no visible error or data, an attacker still extracts information by asking true/false questions. If the page renders differently for 1=1 versus 1=2, the attacker can iterate through character codes one bit at a time to reconstruct entire column values. Automated tools like sqlmap do this at machine speed.

Blind — Time-Based

When the application returns identical output regardless of the query, the attacker injects a time-delay function:

sql
'; IF (1=1) WAITFOR DELAY '0:0:5' --

A five-second response confirms the condition is true. Like boolean blind, this can fully enumerate a database — it just takes more requests.

🚨
DANGER
Automated SQLi tools can test thousands of payloads per minute. A manual code review is not a substitute for automated scanning — by the time a human finds the vulnerable endpoint, an attacker running sqlmap has already dumped the schema.

Know your vulnerabilities before attackers do

Run a free VAPT scan — takes 5 minutes, no signup required.

Book Your Free Scan

Real-World Impact

SQL injection enables attackers to:

    1. Bypass authentication — log in without credentials
    2. Exfiltrate data — dump entire tables including PII, passwords, and financial records
    3. Modify or delete records — UPDATE or DROP TABLE changes that are irreversible
    4. Execute OS commands — on misconfigured databases, xp_cmdshell (MSSQL) or load_file (MySQL) can spawn shell access
The OWASP Top 10 has listed injection as a critical risk in every edition since 2003, with A03:2021 — Injection covering SQL, NoSQL, OS command, and LDAP injection in a single category. For Indian fintech, healthcare, and e-commerce applications handling Aadhaar-linked data or payment records, a single SQLi breach carries both reputational damage and potential liability under the DPDP Act 2023.
pie title OWASP Top 10 A03 Injection — Relative Severity Share by CWE "SQL Injection CWE-89" : 45 "Command Injection CWE-77" : 25 "LDAP Injection CWE-90" : 15 "XPath Injection CWE-643" : 10 "Other Injection" : 5

Prevention — Parameterized Queries and Prepared Statements

The single most effective control is separating code from data. A parameterized query passes user input as a bound parameter, never as part of the SQL string.

Node.js with mysql2 — vulnerable vs fixed:

javascript
// VULNERABLE — direct string interpolation
const query = `SELECT * FROM users WHERE email = '${req.body.email}'`;
db.query(query, callback);

// FIXED — parameterized query
const query = "SELECT * FROM users WHERE email = ?";
db.query(query, [req.body.email], callback);

Python with psycopg2:

python
# VULNERABLE
cursor.execute(f"SELECT * FROM accounts WHERE id = {user_id}")

# FIXED
cursor.execute("SELECT * FROM accounts WHERE id = %s", (user_id,))

Java with PreparedStatement:

java
// VULNERABLE
Statement stmt = conn.createStatement();
stmt.executeQuery("SELECT * FROM orders WHERE customer_id = " + customerId);

// FIXED
PreparedStatement ps = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?");
ps.setInt(1, customerId);
ps.executeQuery();

The database driver treats bound parameters as literal data, never as executable SQL — regardless of what characters they contain.

💡
TIP
If you use an ORM such as Sequelize, Hibernate, Django ORM, or Prisma, you get parameterization by default when you use the query builder. The risk returns when developers bypass the ORM with raw SQL string templates — search your codebase for .query( and raw( calls and audit each one.

Full Prevention Checklist

ControlWhy It HelpsImplementation Notes
Parameterized queries / prepared statementsEliminates code-data confusion at the DB layerMandatory for ALL user-facing inputs
ORM query builder (no raw SQL)Automatically parameterizes most queriesAudit raw(), literal(), query() overrides
Input validation and allowlistingRejects structurally invalid input before it reaches the DBValidate type, length, format — not just "no quotes"
Least-privilege DB userLimits blast radius if injection succeedsApp DB user must not have DROP, CREATE, or FILE grants
Web Application Firewall (WAF)Detects and blocks common SQLi payloads at the edgeDefense-in-depth; not a substitute for parameterization
Error handling — suppress DB errorsPrevents error-based extractionNever expose raw DB errors to end users
Automated VAPT scanningFinds injection points before attackers doRun on every release, not just at launch
⚠️
WARNING
Denylisting — blocking inputs that contain ', --, or UNION — is not a viable defense. Attackers use encoding, case variations, and comment syntax to bypass keyword filters. Parameterized queries are the only reliable control at the query layer.

Least-Privilege Database Users

Most Indian startup applications connect to the database with a root or admin user because it's the path of least resistance during setup. This is a critical misconfiguration. If an attacker achieves SQLi on an admin-credentialed connection, they can drop tables, create backdoor accounts, or read files from the server filesystem.

Create a dedicated application DB user with only the permissions the application actually needs:

sql
-- Create restricted app user
CREATE USER 'bachao_app'@'localhost' IDENTIFIED BY 'strong_random_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON bachao_db.* TO 'bachao_app'@'localhost';
-- No GRANT OPTION, no DROP, no CREATE, no FILE
FLUSH PRIVILEGES;

A read-only reporting user should receive only SELECT. Admin migrations should run under a separate privileged user that is never used by the live application.

🛡️
SECURITY
Rotate database credentials on a schedule and store them in a secrets manager (AWS Secrets Manager, HashiCorp Vault, or at minimum environment variables loaded at runtime — never hardcoded in source code or config files committed to git).

Why Indian Developers Keep Missing This

Several patterns specific to the Indian SMB and startup ecosystem make SQLi disproportionately common:

    1. Tight sprint cycles — security testing is deferred to "after launch"
    2. Legacy codebases — older PHP and raw JDBC codebases predate ORM adoption
    3. Outsourced development — vendor-built applications rarely include security deliverables in scope
    4. Shared hosting — single-user DB setup by default, no separation between app and admin credentials
    5. No automated scanning in CI/CD — deploys ship without injection testing
The Bachao.AI blog covers additional injection classes including NoSQL injection and LDAP injection that affect Node.js and LDAP-backed identity stores.

ORMs Are Not Magic — Know the Exceptions

Prisma, Sequelize, SQLAlchemy, and Hibernate all parameterize standard model queries. But every ORM exposes an escape hatch for raw SQL — and that is where injection vulnerabilities re-enter modern codebases.

Prisma raw query — vulnerable vs fixed:

typescript
// VULNERABLE — template literal bypasses Prisma's parameterization
const users = await prisma.$queryRaw`SELECT * FROM users WHERE name = '${name}'`;

// FIXED — use Prisma.sql tagged template with proper interpolation
import { Prisma } from "@prisma/client";
const users = await prisma.$queryRaw(
  Prisma.sql`SELECT * FROM users WHERE name = ${name}`
);

The Prisma.sql tagged template correctly parameterizes the value; the plain template literal does not.

Bachao.AI, built by Dhisattva AI Pvt Ltd, includes SQL injection detection as part of its automated VAPT scan suite. A free VAPT scan will identify injectable endpoints across your web application without requiring manual testing.

🎯Key Takeaway
SQL injection is preventable with one discipline: never build SQL strings by concatenating user input. Use parameterized queries or ORM query builders for every database call, restrict DB user privileges to the minimum required, and run automated scanning on every release to catch the cases that slip through code review.

External References

Frequently Asked Questions

What is SQL injection in simple terms?
SQL injection is when an attacker enters specially crafted text into a form or URL that tricks your database into running commands the attacker wrote. Instead of just searching for a user, the database might return all users, delete records, or let the attacker log in without a password. It works because the application mixes user input with SQL code without separating them properly.
Is SQL injection still relevant in 2025 with modern frameworks?
Yes. OWASP A03:2021 — Injection remains a top-three web risk. Modern frameworks reduce the risk when used correctly, but injection vulnerabilities re-enter codebases whenever developers use raw SQL inside ORMs, build dynamic queries with string concatenation, or work with legacy code that predates ORM adoption. Automated scanning still finds SQLi in production applications regularly.
What is the difference between blind and in-band SQL injection?
In-band SQLi returns data directly in the HTTP response — either via error messages (error-based) or by appending results to the original query (union-based). Blind SQLi receives no direct data in the response; instead, the attacker infers information from behavioral signals — whether the page loads differently (boolean-based) or whether the server takes longer to respond (time-based). Blind attacks are slower but equally destructive.
Do parameterized queries fully prevent SQL injection?
Parameterized queries — also called prepared statements — are the primary defense and effectively eliminate code-data confusion at the query layer. They should be combined with input validation, least-privilege DB users, and suppressed error messages for defense in depth. Parameterization alone, applied consistently to all queries, closes the vast majority of SQLi attack surface.
How can Indian startups test for SQL injection without a dedicated security team?
Automated VAPT scanning tools can test for SQL injection across all endpoints without requiring manual penetration testing expertise. Running a scan before each major release catches injectable parameters that slip through code review. For CERT-In-aligned assessments required for SEBI or RBI compliance, engage a CERT-In empanelled partner alongside automated tooling.
What Indian regulations increase the consequences of a SQL injection breach?
The DPDP Act 2023 requires organizations to implement reasonable security safeguards for personal data. A breach caused by a preventable vulnerability like SQL injection — where no parameterized queries were used — would be difficult to defend as "reasonable." Regulated sectors face additional obligations under RBI's IT Security Framework, SEBI's CSCRF, and IRDAI guidelines, all of which require documented vulnerability management programs.
BR

Bachao.AI Research Team

Cybersecurity Research

AI-powered security research and threat intelligence from the Bachao.AI team. Covering the latest vulnerabilities, CVEs, and cybersecurity developments affecting Indian businesses.

Get cybersecurity insights for Indian SMBs

Weekly vulnerability alerts, DPDP compliance tips, and security guides. No spam — unsubscribe anytime.

We respect your privacy. Your email is never shared.

Check whether this class of vulnerability is exposed in your systems

Free automated scan — risk score in under 2 hours. No credit card required.

Scan Your Stack for This
Find your vulnerabilitiesStart free scan →