SQL Injection
In one line
SQL injection inserts malicious SQL via user input — prevented by parameterized queries/prepared statements.
In simple words
SQL injection occurs when user input is concatenated directly into a SQL query string. An attacker can input SQL syntax to manipulate the query — reading, modifying, or deleting data.
Example of vulnerable code: query("SELECT * FROM users WHERE name = '" + userInput + "'")
If userInput is ' OR '1'='1, the query becomes: SELECT * FROM users WHERE name = '' OR '1'='1 — returns ALL users.
Worse: '; DROP TABLE users; -- drops the entire users table!
Prevention:
- Parameterized queries — use ? or $1 placeholders, never concatenate
- ORM — uses parameterized queries by default
- Input validation — validate and sanitize input
- Least privilege — database user has minimal permissions
SQL injection is #1 on the OWASP Top 10. Always use parameterized queries.
Example
// VULNERABLE — string concatenation
const name = req.body.name; // "admin' OR '1'='1"
db.query("SELECT * FROM users WHERE name = '" + name + "'");
// Becomes: SELECT * FROM users WHERE name = 'admin' OR '1'='1'
// Returns ALL users! Or worse: "'; DROP TABLE users; --"
// SAFE — parameterized query
const name = req.body.name;
db.query("SELECT * FROM users WHERE name = ?", [name]);
// The database treats name as DATA, not SQL.
// Input "admin' OR '1'='1" safely searches for that literal string.
// SAFE — ORM (uses parameterized queries internally)
const user = await User.findOne({ where: { name: req.body.name } });
// SAFE — prepared statement
const stmt = db.prepare("SELECT * FROM users WHERE name = ?");
const user = stmt.get(req.body.name);Never concatenate user input into SQL. Use parameterized queries (?), prepared statements, or ORMs. The database treats parameters as data, not executable SQL.
Common confusions
Confused with: XSS
The difference: SQL injection attacks the database by injecting SQL into queries. XSS (Cross-Site Scripting) attacks the browser by injecting JavaScript into web pages. SQL injection is prevented by parameterized queries; XSS is prevented by escaping HTML output. Different targets, different defenses.
Related terms
Related Resources
Related Lessons
- Database Security
SQL injection.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.