Search code examples
postgresqlprepared-statement

Conditions in prepared statements in postgres


I need to add a condition inside prepared statement in postgres.

Pseudocode (doesn't works, fires an error "argument of WHERE must be type boolean, not type text"):

if (nameFilter) {
 whereParam = `name LIKE %${nameFilter}%`
} else {
 whereParam = "true"
}
let query = prepare("SELECT * FROM users WHERE $1", whereParam);

Pseudocode (works but looks ugly):

if (nameFilter) {
 likeParam = `%${nameFilter}%`
} else {
 likeParam = "%"
}
let query = prepare("SELECT * FROM users WHERE name LIKE $1", likeParam);

For some reasons(query is really complex with a bunch of AND) manipulations with a string is not an option, so this will not help

if (nameFilter) {
 q = `SELECT * FROM users WHERE name LIKE $1`
} else {
 q = "SELECT * FROM users"
}
let query = prepare(q, nameFilter);

Desirable to have statement similar to SELECT * FROM users WHERE $1 AND $2 AND $3 ...

Any suggestions?


Solution

  • This query will work for you.

    select * from users where
      case
        when coalesce($1, '') = '' then true 
        else (name ~ $1)
      end;