I am setting up an REST
service and I am using postgres
as the data store. I want to know how to set up a postgres
query to use optional parameters. ie:
SELECT * from users where hair_color = $1 and eye_color = $2
Where $1 and $2 come from the request: [req.body.hair_color, req.body.eye_color]
What if the user didn't pass in eye_color
and in that case I wanted all eye colors. I assume that I don't have to make a bunch of if/else
statements here. What is the concise way of creating this query?
Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext); .
You construct a pattern by combining literal values with wildcard characters and use the LIKE or NOT LIKE operator to find the matches. PostgreSQL provides you with two wildcards: Percent sign ( % ) matches any sequence of zero or more characters. Underscore sign ( _ ) matches any single character.
In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.
<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.
Here I've made both hair_color
and eye_color
optional. (Pass your language's equivalent of NULL).
SELECT * from users where ($1 is null or hair_color = $1) and ($2 is null or eye_color = $2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With