Categories
JavaScript Answers

How to execute a “WHERE col IN ()” query with node-postgres?

Spread the love

Sometimes, we want to execute a "WHERE col IN ()" query with node-postgres.

In this article, we’ll look at how to execute a "WHERE col IN ()" query with node-postgres.

How to execute a "WHERE col IN ()" query with node-postgres?

To execute a "WHERE col IN ()" query with node-postgres, we can use the client.query method.

For instance, we write

const ids = [1, 3, 4];

const q = client.query('SELECT Id FROM MyTable WHERE Id = ANY($1::int[])', [ids]);

q.on('row', (row) => {
  console.log(row);
})

to call client.query with the parameterized SQL string, and an array of values we set as the parameter values.

We add ids as the value of the value of ANY($1::int[]).

Then we call q.on with 'row' to return the query results and get the result from the row parameter.

Conclusion

To execute a "WHERE col IN ()" query with node-postgres, we can use the client.query method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *