Node-postgres prepared statements with conditional arguments

Viewed 407

Is there a way to query something where you hava many conditions that can be undefined (not required)

const c = {
  id?: number
  type?: string
}

const sql = `SELECT * FROM smth WHERE id=$1 AND type=$2`

query(sql , [c.id, c.type])
1 Answers

You could use

const sql = `SELECT * FROM smth WHERE ($1::int IS NULL OR id=$1) AND ($2::text IS NULL OR type=$2)`;

but in general this is the place where query builder libraries are the appropriate solution.

Related