Ali Mamedov
Ali Mamedov

Reputation: 5256

PostgreSQL dynamic conditions in WHERE

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?

Upvotes: 0

Views: 633

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270401

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.

Upvotes: 1

Related Questions