4

I'm trying to write a node-postgres query that takes an integer to use in an interval as a parameter:

  const query = {
    text:
      `SELECT
        foo 
        FROM bar 
        WHERE 
          DATE(created_at) >= DATE(NOW()) - INTERVAL '$1 DAYS';`,
    values: [daysAgo]
  }

When I run this, it gives this error message indicating it's not seeing the $1 because it's enclosed in single quotes:

bind message supplies 1 parameters, but prepared statement "" requires 0

Is there a supported way to do this? If not, what is the best work around?

alexroussos
  • 2,671
  • 1
  • 25
  • 38

1 Answers1

6

I found this reference which shows you can use the convention of '1 DAY' * X.

I was able to get this working thus:

   (async () => {
       const { rows } = await pgpool.query(`
          SELECT id, name FROM users 
           WHERE DATE(created) <= DATE(NOW()) - INTERVAL '1 DAY' * $1;`,
           [req.params.daysAgo]);
rotarydial
  • 2,181
  • 2
  • 23
  • 27