Node-postgres: Conditional statements based on query strings

Created on 29 Jul 2020  路  3Comments  路  Source: brianc/node-postgres

Hey all. I've been looking for this but I can't find an answer.

Is there a way to add statements to my query based on a conditional statement?

For example, my query:
SELECT * FROM users

If the server also receives from the front-end a query string like name="John" I want to add this to my pre-defined query:
SELECT * FROM users WHERE name = 'John'

What I am trying to accomplish here is to have a default query, that will change based on FILTERS and SEARCH made by the user on the front-end.

Thank you in advance.

question

Most helpful comment

Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?

const sql = `
  select *
    from users
   where (
     case when $1 is not null
       then name = $1
       else true
     end
   )
`

const value = [request.query.name]

Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?

https://www.npmjs.com/search?q=postgres%20query%20builder

All 3 comments

Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?

const sql = `
  select *
    from users
   where (
     case when $1 is not null
       then name = $1
       else true
     end
   )
`

const value = [request.query.name]

Hi @lucasmrl this is just an idea, but what about something like this? Not too sure it would scale to more complex stuff though. Maybe check out a query builder?

https://www.npmjs.com/search?q=postgres%20query%20builder

This is eventually a job for query builders or in-query logic (including stored procedures), yep. One popular query builder is Knex.js.

Thank you, guys! I decided to do something simple so I went with @thebearingedge , but I will definitely take a look at Knex.js!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gajus picture gajus  路  4Comments

tonylukasavage picture tonylukasavage  路  4Comments

wrod7 picture wrod7  路  4Comments

v1co1n picture v1co1n  路  4Comments

chovy picture chovy  路  3Comments