Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query postgres on optional params?

Tags:

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?

like image 476
jhamm Avatar asked Jan 11 '14 12:01

jhamm


People also ask

How do you do a case insensitive search in PostgreSQL?

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); .

How do I do a wildcard search in PostgreSQL?

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.

How do I select a variable in PostgreSQL?

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.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.


1 Answers

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); 
like image 198
David-SkyMesh Avatar answered Sep 26 '22 02:09

David-SkyMesh