# What is SQL Injection?
SQL Injection (SQLi) is a security vulnerability where an attacker interferes with database queries executed by an application. It allows malicious users to view sensitive data, bypass authentication, modify or delete database tables, and in some circumstances, gain shell execution on the underlying database server.
# How SQL Injection Works
SQLi occurs when user input is concatenated directly into SQL statements without proper validation, parameterization, or escaping.
-- Vulnerable query constructed by backend:
SELECT * FROM users WHERE username = 'admin' AND password = 'user_input';
-- If user enters: ' OR '1'='1
-- The executed query becomes:
SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';# Types of SQL Injection
SQL injection attacks fall into three primary categories:
- In-Band SQLi (Classic): Results are reflected directly on the same channel (e.g. Error-based or UNION-based).
- Inferential SQLi (Blind): No data is printed directly on page, but attacker reconstructs information by asking true/false questions (Boolean-based or Time-based).
- Out-of-Band SQLi: Attacker triggers DNS or HTTP requests from the database server to an external listener.
# Vulnerable vs. Secure Code Example
Let's contrast insecure query construction with modern parameterized prepared statements:
// INSECURE (Vulnerable to SQLi):
// const query = `SELECT * FROM accounts WHERE id = '${req.body.id}'`;
// SECURE: Parameterized Prepared Statement
const text = 'SELECT id, username, email FROM accounts WHERE id = $1 AND active = $2';
const values = [req.body.id, true];
const result = await db.query(text, values);# Prevention & Remediation
Preventing SQL injection requires adhering to standard defensive development patterns:
Always use Prepared Statements with Parameterized Queries or Object Relational Mapping (ORM) query builders. Never concatenate untrusted strings into database queries.
# Conclusion
SQL injection remains one of the most devastating web vulnerabilities. By enforcing strict parameterization, minimal database account privileges, and robust automated security testing in CI/CD, applications can completely eliminate SQLi threats.