IN clause in mysql nodejs

If you are using node module like mysql, the 2nd approach should work.

var query=select * from User where userid in (?);
var data=['a','b','c'];
var queryData=[data];

conn.query(query, queryData, function (err, results) {})

According to the documentation, "Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'". So this approach should work (I have used it practically).


If you pass an array to the parameter it works with node mysql2. Parameters are already passed as arrays, so your first parameter needs to be an array [[1,2,3]].

select * from User where userid in (?)
const mysql = require('mysql2/promise');

async function main(){
  let db = await mysql.createPool(process.env.MYSQL_URL);
  let SQL = 'select * from User where userid in (?)';

  let [res, fields] = await db.query(SQL, [[1,2,3]]);
  console.log(res)
  return res;
}

main().then(() => {process.exit()})

Revisiting this, since the original approach on the question is valid, but with some caveats. If your only escaped argument is the one on the IN clause, then you have to specify it as nested array; something like: [['usrId1', 'usrId2', 'usrIdN']]. This is because the un-escaping functionality expects an array, replacing each '?' with the corresponding array element. So, if you want to replace your only '?' with an array, that array should be the first element of all arguments passed. If you had more than one '?', the syntax is more intuitive, but at the end consistent and the same; in this case, you could have your arguments similar to: ['myOtherArgument1', 'myOtherArgument2', ['usrId1', 'usrId2', 'usrIdN'], 'myOtherArgument3']

Tags:

Mysql

Node.Js