Node-postgres: How can I execute WHERE $1 IS NULL

Created on 27 Nov 2018  路  1Comment  路  Source: brianc/node-postgres

I want to query postgres on optional params in postgres using ($1 IS NULL) as the following example:

SELECT * from users where ($1 is null or hair_color = $1) and ($2 is null or eye_color = $2);

but I have an error:
error: could not determine data type of parameter $1

Reference:
https://stackoverflow.com/a/21062210/9392229

question

Most helpful comment

PostgreSQL needs to know the type of a parameter the first time you use it. Sometimes it can tell from context, like in hair_color = $1, but $1 is null would work for any type. You can rearrange the query:

select * from users where (hair_color = $1 or $1 is null) and (eye_color = $2 or $2 is null);

or specify the correct explicit type, e.g. if the parameters should be text:

select * from users where ($1::text is null or hair_color = $1) and ($2::text is null or eye_color = $2);

>All comments

PostgreSQL needs to know the type of a parameter the first time you use it. Sometimes it can tell from context, like in hair_color = $1, but $1 is null would work for any type. You can rearrange the query:

select * from users where (hair_color = $1 or $1 is null) and (eye_color = $2 or $2 is null);

or specify the correct explicit type, e.g. if the parameters should be text:

select * from users where ($1::text is null or hair_color = $1) and ($2::text is null or eye_color = $2);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

AhmedBHameed picture AhmedBHameed  路  3Comments

gpanainte picture gpanainte  路  3Comments

chovy picture chovy  路  3Comments

frmoded picture frmoded  路  3Comments

Cosrnos picture Cosrnos  路  3Comments