Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL conditional where clause

Tags:

In my Ruby on Rails app I'm using blazer(https://github.com/ankane/blazer) and I have the following sql query:

SELECT *
FROM survey_results sr
LEFT JOIN clients c ON c.id = sr.client_id
WHERE sr.client_id = {client_id}

This query works really well. But I need to add conditional logic to check if client_id variable is present. If yes then I filter by this variable, if not then I not launching this where clause. How can I do it in PostgreSQL?

like image 808
Mateusz Urbański Avatar asked Aug 29 '17 11:08

Mateusz Urbański


People also ask

Can I use case in where clause PostgreSQL?

The PostgreSQL CASE expression is the same as IF/ELSE statement in other programming languages. It allows you to add if-else logic to the query to form a powerful query. Since CASE is an expression, you can use it in any places where an expression can be used e.g., SELECT , WHERE , GROUP BY , and HAVING clause.

Can we use if condition in PostgreSQL query?

In PostgreSQL, the if-statement is one of the most valuable and frequently used control statements. The If statement executes only those expressions that satisfy the specified condition. If an expression doesn't satisfy the specified criteria, then the if-statement moves the control to the next statement.

What is the purpose of where clause in PostgreSQL?

The PostgreSQL WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple tables. If the given condition is satisfied, only then it returns specific value from the table.

What can be the condition in where clause in a SQL query?

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.


2 Answers

Check if its null OR your condition like this:

WHERE {client_id} IS NULL OR sr.client_id = {client_id} 

The WHERE clause evaluate as follow: If the variable is empty, then the WHERE clause evaluate to true, and therefore - no filter. If not, it continue to the next condition of the OR

like image 155
sagi Avatar answered Sep 20 '22 07:09

sagi


If anyone faced with the psql operator does not exist: bigint = bytea issue, here is my workaround:

WHERE ({client_id} < 0 AND sr.client_id > {client_id}) OR sr.client_id = {client_id} 

Please consider that, client_id generally cannot be negative so you can use that information for eleminating the operation cast issue.

like image 43
Furkan Yavuz Avatar answered Sep 19 '22 07:09

Furkan Yavuz