Search code examples
postgresqlnode-postgres

Node-postgres prepared statements with conditional arguments


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])

Solution

  • 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.