SQL injection: unescaped user input in query
Quick summary
You built a SQL string by concatenating user input — an attacker can inject SQL commands that the database executes.
Why this happens
User input is concatenated directly into a SQL string without escaping or parameterization
Dynamic SQL is built with string interpolation instead of parameterized queries
User input is used in ORDER BY or table name clauses where parameterization is not straightforward
Minimal example
const name = req.body.name; // user input: ' OR 1=1 --
await db.query('SELECT * FROM users WHERE name = ' + "'" + name + "'");
// Result: SELECT * FROM users WHERE name = '' OR 1=1 --' — returns all users!const name = req.body.name;
await db.query('SELECT * FROM users WHERE name = $1', [name]);
// Parameterized: the input is treated as a value, not SQL codeParameterized queries separate the SQL code from the data values, making it impossible for user input to alter the SQL structure.
How to diagnose
Review all SQL construction code for string concatenation with user input
Test with input containing SQL metacharacters like single quotes and semicolons
Use a static analysis tool that detects SQL injection vulnerabilities
How to fix
Use parameterized queries with placeholders: WHERE name = $1 instead of string concatenation
Use an ORM or query builder that automatically parameterizes user input
For dynamic identifiers (table/column names), use a whitelist of allowed values
How to prevent
Always use parameterized queries or prepared statements — never concatenate user input into SQL
Use a query builder or ORM and validate dynamic identifiers against a whitelist
Related Resources
Related Glossary
Related Lessons
- SQL Security
Learn about SQL injection.