Home > Enterprise >  Correct way of using node-postgres select with IN clause
Correct way of using node-postgres select with IN clause

Time:09-28

I am trying to workout how to pass in a comma sepated string of values into a postgres select within in clause query using node-postgres but unfortunately can't seem to get it working and can't find any examples.

I have the following code:

function getUser() {
  let inList = "'qwerty', 'qaz'";

  const result = await pgPool.query("SELECT name FROM my_table WHERE info IN ($1)", [inList]);  
  if (result.rowCount == 1) return result.rows.map(row => row.name)
  return false
}

Basically want the end result query to process:

SELECT name FROM my_table WHERE info IN ('qwerty', 'qaz')

Unsure if this is actually the correct way of doing this with pgPool?

CodePudding user response:

The right way is in the FAQ on Github --> https://github.com/brianc/node-postgres/wiki/FAQ#11-how-do-i-build-a-where-foo-in--query-to-find-rows-matching-an-array-of-values

You should be able to do it that way :

 pgPool.query("SELECT name FROM my_table WHERE info = ANY ($1)", [jsArray], ...);
  • Related