How can I create a condtional WHERE clause that depends on the input values in PostgreSQL?

66 Views Asked by At

I am using the tokio_postgres crate with Rust. Of course, I can create two seperate queries and perform condition checking on my input values in my code, although I am looking for a way to do it through the SQL query.

I am passing two values into my query $1 = task_id, $2 = user_uuid

My (pseduo) statement looks like this:

let statement =

SELECT status FROM assignments 
WHERE task_id = $1 OR user_uuid = $2;

I am calling it as follows:

db.query(&statement, &[&task_id, &user_uuid])

task_id: Option

user_uuid: Option

So, basically, task_id or user_uuid will always be null (or "None" in rust terms).

In my SQL query, how can I conditionally use one or the other, based on which one contains a value? So, if task_id is null, then the query will be

SELECT status FROM assignments 
user_uuid = $2;

Versus, if user_uuid is null, the query will be

SELECT status FROM assignments 
WHERE task_id = $1;

Should this simply be done in the Rust code? I feel like there is an easy way to do it with the SQL query though.

0

There are 0 best solutions below