Parameterized query
- Node.js course
- Advanced
- Lesson 33/83
- 5 min
Learn SQL injection protection with parameterized queries.
Parameterized query
A parameterized query separates the SQL string from user data. The SQL string uses placeholders like $1, $2; the actual values are passed as a separate array.
Example: pool.query("SELECT * FROM users WHERE email = $1", [email]). This prevents SQL injection; the user data never merges with the SQL string. PostgreSQL substitutes the placeholders safely. Parameterized queries are the golden rule of database security.
Why parameterized?
A non-parameterized query is dangerous. The pattern pool.query("SELECT * FROM users WHERE name = '" + name + "'") lets a malicious name value alter the SQL. For example name = "' OR '1'='1" returns all users.
With a parameterized query this is impossible. The $1 placeholder represents a single value; it cannot change the SQL structure. Always use parameterized queries; never concatenate user data directly into SQL.
Practice Log the query string
Define an SQL string: SELECT * FROM users WHERE id = $1. Assign it to a text variable. Log text with console.log.
Starter code
// define the query string
// log the stringSample solution
const text = "SELECT * FROM users WHERE id = $1";
console.log(text);Expected output
SELECT * FROM users WHERE id = $1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
$1 |
Placeholder |
values array |
Parameter values |
pool.query |
Runs a query |
SQL injection |
Attack type |
2 Complete the placeholder
const text = "SELECT * FROM users WHERE id = ____";
const text = "SELECT * FROM users WHERE id = $1";
Explanation: In PostgreSQL $1 is a parameter placeholder.
3 What does a parameterized query prevent?
- SQL enjeksiyonunu Correct answer
- Memory leaks
- A CSS error
- A network slowdown
Explanation: A parameterized query prevents SQL injection.