Knex supports several ways to bind parameters in knex.raw() to ensure values are properly escaped:
Positional Bindings
?: Interpreted as a value.??: Interpreted as an identifier (e.g., table or column names).
Named Bindings
:name: Interpreted as a value.:name:: Interpreted as an identifier.
Named bindings are processed as long as the provided value is not undefined.
Single Bindings
If you only have one binding, you can pass the value directly as the second argument to .raw() instead of an array.
Array Bindings
Knex does not have a unified syntax for array bindings (like IN (?)). You must manually generate the correct number of placeholders in your SQL string.
// Positional: Identifier and Value
knex('users').where(knex.raw('?? = ?', ['user.name', 1]))
// Named: Identifier and Value
const raw = ':name: = :thisGuy or :name: = :otherGuy or :name: = :undefinedBinding'
knex('users').where(knex.raw(raw, {
name: 'users.name',
thisGuy: 'Bob',
otherGuy: 'Jay',
undefinedBinding: undefined
}))
// Single binding shortcut
knex.raw('LOWER("login") = ?', 'knex')
// Manual Array binding for IN clauses
const myArray = [1, 2, 3]
knex.raw('select * from users where id in (' + myArray.map(_ => '?').join(',') + ')', [...myArray]);