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
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);
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 nullwould work for any type. You can rearrange the query:or specify the correct explicit type, e.g. if the parameters should be text: