Sub topic 9
Practical Pattern: Parameterized SQL Queries
This chapter assumes you already know how a tag receives its strings array and values, and how reduce without an initial value interleaves them. Here you will use that same mechanism to build SQL queries that resist injection.
The Problem with Plain Interpolation
An untagged template literal joins everything into one string. If any part of that string came from a user, the database cannot tell your SQL apart from their input:
const name = "x' OR '1'='1";
const query = `SELECT * FROM users WHERE name = '${name}'`;
console.log(query);
// SELECT * FROM users WHERE name = 'x' OR '1'='1'The quote inside name closes the string literal early, and the condition now matches every row. This is SQL injection. Escaping quotes by hand is fragile. The reliable fix is a parameterized query: you send the SQL text with placeholders, and you send the values separately. The database driver binds each value as data, so it can never be read as SQL.
A Tag That Separates Text from Values
A tag already gets the SQL you wrote (strings) separately from the values you inserted (values). All it has to do is keep them apart. Instead of returning a string, it returns an object:
function sql(strings, ...values) {
return {
text: strings.reduce((query, str, i) => query + '$' + i + str),
values,
};
}
const name = "x' OR '1'='1";
const status = 'active';
const q = sql`SELECT * FROM users WHERE name = ${name} AND status = ${status}`;
console.log(q);
// {
// text: 'SELECT * FROM users WHERE name = $1 AND status = $2',
// values: [ "x' OR '1'='1", 'active' ]
// }Because reduce starts from strings[0], the first callback runs with i = 1. That makes the placeholders start at $1, which is what PostgreSQL expects. The hostile input stays in values and never reaches text.
The { text, values } shape is deliberate. The pg driver for Node.js accepts exactly this object, so client.query(sql\...\) works without any glue code.
Placeholder Styles Differ by Database
Each database expects its own placeholder syntax. The tag is the only place you need to change:
| Database / driver | Placeholder | Example text |
|---|---|---|
| PostgreSQL (`pg`) | `$1`, `$2`, ... | `WHERE id = $1` |
| MySQL (`mysql2`), SQLite | `?` | `WHERE id = ?` |
| SQL Server (`mssql`) | `@p1`, `@p2`, ... | `WHERE id = @p1` |
What Production Libraries Add
Libraries such as postgres (postgres.js), slonik, and sql-template-strings are built on this same idea. They also handle details the minimal tag skips:
- Nesting fragments, so that a
sqlresult inside anothersqlcall is merged in and not bound as a single value. - Expanding arrays for
IN (...)lists. - Safe helpers for identifiers, such as
sql(identifierName)in postgres.js.
The minimal tag above is enough to see the mechanism. In production, use a maintained library.
Exercise
Rewrite the sql tag so it produces ? placeholders for MySQL. Then say what it returns for sqlUPDATE t SET a = ${1}, b = ${'x'} WHERE id = ${9}.
Show answer
function sql(strings, ...values) { return { text: strings.join('?'), values }; } returns { text: 'UPDATE t SET a = ?, b = ? WHERE id = ?', values: [1, 'x', 9] }. The placeholders carry no numbers, so joining the static parts with '?' is enough. There is always exactly one fewer value than string parts, so the count matches.
Exercise
A teammate writes sqlSELECT * FROM users ORDER BY ${column} to let users pick a sort column. Why does this fail, and how should it be fixed?
Show answer
The tag turns ${column} into a placeholder ($1), and databases cannot bind identifiers as parameters, so the query is either rejected or sorts by a constant. Check column against an allowlist such as ['name', 'created_at'], then put the approved name into the SQL text itself, for example with a library's identifier helper. Never pass the raw input through.