0

We have one table: categories

|---------------------|------------------|
|     category_id     |        name      |
|---------------------|------------------|
|          1          |     'text 1'     |
|---------------------|------------------|
|          2          |     'text 2'     |
|---------------------|------------------|

We need to do this:

Pseudo SQL code:

SELECT * FROM categories WHERE case when $1 != 0 then category_id = $1 end; 

$1 - input parameter's value

Is It possible to do it in PostgreSQL with one SQL query?

8
  • It is possible, but usually this leads to inefficient (=slow) execution plans. Commented Jan 27, 2020 at 7:30
  • 1
    Yes, exactly. In most cases this will be way more efficient Commented Jan 27, 2020 at 7:36
  • 1
    WHERE $1 =0 OR $1 = category_id Commented Jan 27, 2020 at 8:07
  • 1
    Or WHERE $1 !=0 AND $1 = category_id in which case the comment above (by Nick) applies. Commented Jan 27, 2020 at 8:32
  • 1
    That won't work as written, since the CASE clause will return a null value when $1 = 0, and that's not a boolean value. Commented Jan 27, 2020 at 11:41

1 Answer 1

1

I am guessing that you want:

SELECT c.*
FROM categories c
WHERE $1 = 0 OR c.category_id = $1;

This returns all rows if the input parameter is 0 and just the matching row otherwise.

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

1 Comment

GordonLinoff, thx for the answer. @a_horse_with_no_name adviced me to avoid using such SQL queries because of performance issues. Programmatically generating SQLs are more preferable in case of highload apps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.