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?
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With