37

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?

3 Answers 3

71

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

Sign up to request clarification or add additional context in comments.

4 Comments

How can we use it for multiple values?
Can you give an example of what you mean? @Ulvi
I found the answer. I wanted to have multiple filters. I wrapped each of them with brackets and wrote AND among them.
for strings, we can equate with '' as well
1

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.

Comments

0

My solution:

I use spring data jpa, native query.

Here is my repository interface signature.

@Query(... where (case when 0 in :itemIds then true else i.id in :itemIds end) ...)
List<Item> getItems(@Param("itemIds) List<Long> itemIds)

Prior calling this method, I check if itemIds is null. If yes, I set value to 0L:

if(itemIds == null) {
   itemIds = new ArrayList<Long>();
   itemIds.add(0L);
}
itemRepo.getItems(itemIds);

My IDs starts from 1 so there is no case when ID = 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.