What Is SQL Injection?
SQL injection is a vulnerability where an attacker inserts malicious SQL code into application queries through user input fields. If the application builds SQL queries by concatenating user input directly, the attacker can read, modify, or delete database data, bypass authentication, and in some cases execute operating system commands.
Types of SQL Injection?
Classic SQL Injection
Directly manipulates the query by terminating the string and adding new SQL commands.
Username: admin' OR '1'='1' --
Blind SQL Injection
No visible error output — attacker infers data by observing response differences (boolean-based) or timing delays (time-based).
id=1 AND IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0)
Union-based SQL Injection
Uses UNION SELECT to combine results from other tables into the response.
id=1 UNION SELECT username, password FROM users --
How to Prevent It
# 1. Parameterized queries (prepared statements) — THE fix
# Python (psycopg2)
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
# Node.js (pg)
client.query('SELECT * FROM users WHERE id = $1', [userId])
# Java (JDBC)
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setInt(1, userId);
# 2. ORM — inherently parameterized
# Django
User.objects.filter(id=user_id)
# SQLAlchemy
session.query(User).filter(User.id == user_id)
# 3. NEVER do this:
# query = "SELECT * FROM users WHERE id = " + user_input // VULNERABLE
Real-World Impact
Complete database compromise, authentication bypass, data exfiltration, data deletion, privilege escalation to database admin, and potentially remote code execution via xp_cmdshell (SQL Server) or LOAD_FILE (MySQL).
Related Questions
Scan your system prompt with LochBot — free, client-side, no data sent anywhere.