Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])
like image 623
ZiiMakc Avatar asked Jul 09 '26 20:07

ZiiMakc


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.

like image 92
Bergi Avatar answered Jul 14 '26 03:07

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!