SQL Injection
Web Security

SQL Injection

A complete guide to SQL Injection (SQLi): how untrusted inputs manipulate database queries, in-band vs blind attacks, and parameterized defense.

Think about how an automated teller machine (ATM) works. When you insert your card and request $50, the machine takes that number and processes a standard withdrawal for that specific amount. Now imagine if someone typed a message into the withdrawal box like: 'Withdraw $50, and also increase my balance by $1,000,000.' A well-built system treats the entire input simply as a number, finds it invalid, and rejects it. But if the software carelessly glued that text directly into its internal database commands, the database might actually execute both instructions. That is the core idea behind SQL Injection (SQLi). It happens when an application takes user input (such as text from a login box, search bar, or web form) and pastes it directly into a database query. Because the application fails to separate the user's data from the database's code instructions, an attacker can manipulate the query and take control of database operations.

Definition

SQL Injection (SQLi) is a security vulnerability where untrusted user input is combined directly into a database query, allowing an attacker to change the query structure, bypass authentication, view private data, alter records, or execute administrative commands.

Why It Matters

Databases store an organization's most critical information: user passwords, payment records, personal communications, and customer data. A successful SQL injection attack can allow someone on the internet to bypass login screens without a password, download entire database tables in minutes, or delete essential business records. Because relational databases are used by nearly every web application, preventing SQL injection is a fundamental requirement of web development.

How It Works

SQL injection occurs when an application fails to separate executable code from user-supplied data: 1. How a Vulnerable Query Operates: Consider a typical login query written with string concatenation: `SELECT * FROM users WHERE email = '" + userInput + "' AND password = '" + passInput + "';` If an attacker enters the following into the email field: `admin@example.com' OR '1'='1' --` The database combines the text directly into the command: `SELECT * FROM users WHERE email = 'admin@example.com' OR '1'='1' --' AND password = '...';` Here is what happens: • The single quote (`'`) closes the email text field early. • The `OR '1'='1'` condition is always true for every row in the table. • The double hyphen (`--`) tells the database that everything following it is a comment, completely ignoring the password check. • Result: The database returns the first user found (often the administrator account), logging the attacker in without a valid password. 2. Types of SQL Injection: • In-Band SQLi: The attacker sends the injection payload and sees the results through the same channel. This includes Error-Based SQLi (forcing the database to reveal information inside error messages) and UNION-Based SQLi (combining results from other tables into the visible output). • Blind (Inferential) SQLi: The application does not show database errors or raw data on screen. The attacker extracts information character by character by asking true-or-false questions: - Boolean Blind: Observing whether a web page changes or loads differently when a statement is true versus false. - Time-Based Blind: Telling the database to pause for several seconds if a condition is true (using sleep commands). If the page takes longer to respond, the condition was true. • Out-of-Band SQLi: The database is instructed to make an external network connection (such as a DNS lookup or HTTP request) to an attacker-controlled server to send back data. 3. The Standard Defense: Parameterized Queries (Prepared Statements): Prepared statements solve this problem by separating the query structure from the data values. The database compiles the query structure first (`WHERE email = ?`). The user's input is then supplied separately as plain data. Even if the user submits `' OR '1'='1' --`, the database searches literally for an account whose email matches that exact text string. The input is never executed as code.

Vulnerable Dynamic SQL vs Secure Prepared Statement Execution

1. Attacker Payload
An attacker enters: `' OR 1=1; DROP TABLE users; --` into a web input field
2A. Vulnerable Query Execution
The server concatenates input directly into the query, causing the database to interpret the payload as SQL commands
2B. Secure Prepared Statement
The database pre-compiles the query structure first: `SELECT * FROM products WHERE name = ?`
3. Parameter Value Binding
The user input is passed strictly as a literal text parameter, never as executable code
4. Safe Database Execution
The database searches for a product whose literal name matches the input text, preventing any injection attack

Key Points

  • SQL injection happens when untrusted user input modifies the intended structure of a database query.
  • Prepared statements (parameterized queries) prevent SQLi by separating code compilation from data values.
  • Simple input filters and character blocklists are unreliable because attackers can bypass them with alternative encodings.
  • Blind SQL injection allows attackers to extract data character by character using timing delays or true/false page responses.
  • ORM frameworks use parameterization by default, but raw query methods must be handled with care.

Steps

  1. Audit Code for String Concatenation

    Scan codebases using Static Application Security Testing (SAST) tools to flag places where raw string interpolation is used inside SQL queries.

  2. Use Parameterized Queries Everywhere

    Write database operations using parameterized queries with placeholders (`?` in MySQL, `$1` in PostgreSQL) for all user-supplied values.

  3. Follow Safe ORM Query Guidelines

    When using ORM libraries (such as Prisma, TypeORM, or SQLAlchemy), rely on standard query builder methods and avoid unescaped raw SQL queries.

  4. Enforce Least Privilege on the Database

    Grant web application database accounts only the permissions they require (such as SELECT and INSERT) and disallow administrative actions like DROP TABLE.

  5. Deploy a Web Application Firewall (WAF)

    Use a WAF at the network edge with OWASP Core Rule Sets to detect and block common automated injection scanners before requests reach servers.

Examples

The School Enrollment Name Analogy

A well-known programming comic features a student named `Robert'); DROP TABLE Students;--`. If a school database takes that name and concatenates it directly into an SQL INSERT command, the database finishes the insert, runs the DROP TABLE command, and ignores the rest of the query. Using prepared statements prevents this mistake by ensuring the name is always treated strictly as plain text.

Real-World Examples

The Heartland Payment Systems Breach (2008)

Attackers found an SQL injection vulnerability in a public web form at Heartland Payment Systems. They used the vulnerability to break into internal payment processing networks and capture credit card numbers over several months, resulting in over $140 million in penalties and recovery costs.

Technical Examples

Vulnerable Dynamic Query vs Production Parameterized Query in PostgreSQL / TypeScripttypescript
import { Pool } from "pg";
const pool = new Pool();

// ─── 1. VULNERABLE IMPLEMENTATION (DO NOT USE!) ─────────────────────
// String concatenation allows SQL injection to dump or alter records!
export async function vulnerableSearchUser(userInput: string) {
  // DANGEROUS: If userInput is: test' UNION SELECT id, password_hash, token FROM auth_tokens --
  const query = `SELECT id, email, username FROM users WHERE username = '${userInput}'`;
  const result = await pool.query(query);
  return result.rows;
}

// ─── 2. SECURE IMPLEMENTATION (Parameterized Prepared Statement) ────
export async function secureSearchUser(userInput: string) {
  // $1 is a typed parameter placeholder; database engine pre-compiles query structure
  const query = "SELECT id, email, username FROM users WHERE username = $1";

  // The database driver sends userInput separately in the parameter array
  const result = await pool.query(query, [userInput]);
  return result.rows;
}

// ─── 3. SECURE ORM USAGE (Prisma Example) ──────────────────────────
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

export async function prismaSearch(userInput: string) {
  // Standard Prisma query builder automatically parameterizes queries
  return await prisma.user.findMany({
    where: { username: userInput }, // Completely safe from SQL injection
  });
}
In the secure implementation, `$1` represents a parameter placeholder. The database compiles the query structure first, and the input value is sent separately. Even if the input includes SQL keywords, the database treats it strictly as a plain text string.

Dynamic Concatenated SQL vs Parameterized Prepared Statement

AspectDynamic Concatenated SQLParameterized Prepared Statement
Execution MethodQuery structure and user data are combined into one stringQuery structure is compiled first; user data is passed separately
SQLi ProtectionVulnerable to in-band, blind, and out-of-band injection attacksProtects against SQL injection completely
PerformanceDatabase must parse and plan the query on every single executionDatabase can cache and reuse the pre-compiled execution plan
Special CharactersSingle quotes and semicolons can break syntax or alter queriesQuotes and special characters are safely stored as plain text

Understanding How Blind SQL Injection Scripts Work

Security testers demonstrate Blind SQL injection by using automated scripts to test characters one by one: ```python import requests, time TARGET_URL = 'https://example.com/api/products' CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_' extracted_data = '' for position in range(1, 33): # Extract a 32-character hash for char in CHARS: payload = f"1' AND IF(SUBSTRING((SELECT password_hash FROM users WHERE id=1),{position},1)='{char}', SLEEP(3), 0) -- " start = time.time() requests.get(TARGET_URL, params={'id': payload}) if time.time() - start >= 3: extracted_data += char print(f'Found character {position}: {char}') break ``` Defense: Using prepared statements completely stops this attack because the database treats the entire input as a literal search value rather than evaluating the sleep function.

Advantages

  • Eliminates Root Cause: Parameterized queries remove the ability for user input to become executable code.
  • Performance Optimization: Pre-compiled statements allow the database to reuse query execution plans efficiently.
  • Clean Code Structure: Keeps SQL command logic clearly separated from dynamic user data.

Limitations

  • Dynamic Identifiers: Prepared statements parameterize data values, but cannot parameterize table names or sort directions (ASC/DESC), which must be checked against explicit allowlists.
  • Legacy Codebases: Updating older systems to use prepared statements everywhere requires thorough testing.

Interview Questions

How does a Time-Based Blind SQL Injection attack work?

In a Time-Based Blind SQL injection attack, the application does not display database errors or query results on screen. Instead, the attacker injects a conditional statement paired with a database sleep function (such as `pg_sleep(5)` or `WAITFOR DELAY`). If the application takes several seconds to respond, the attacker knows their condition was true. By repeating this process for each character, an attacker can extract data from the database one letter at a time.

Practice Questions

  1. Explain how an attacker uses a UNION SELECT statement to extract data from a different database table in an in-band SQL injection vulnerability.
  2. Check a project you have worked on: Are all database interactions using parameterized queries or safe ORM calls?