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.

Frequently Asked Questions

What is SQL injection?

SQL injection is when an attacker manipulates database queries by inserting malicious SQL code through user input. If the application concatenates user input directly into SQL strings, the attacker can read, modify, or delete any data in the database.

How do I prevent SQL injection?

Use parameterized queries (prepared statements) for all database interactions. Never concatenate user input into SQL strings. ORMs like Django ORM, SQLAlchemy, and Sequelize handle parameterization automatically.

Is SQL injection still common in 2026?

Yes. SQL injection has been in the OWASP Top 10 since its inception and remains one of the most exploited vulnerabilities. While frameworks make prevention easier, legacy code and raw SQL queries in new code continue to introduce the vulnerability.