0

Using Birt reporting which allows injecting parameter in a query as follow:

SELECT *
FROM foo 
WHERE bar = ?

The question mark comes from a drop down list. Among these values, 'All' can be selected, meaning there are no WHERE clause.

Is there a way to have conditional value in the WHERE clause such as below or an equivalent ?

WHERE
  CASE WHEN ? IS NULL 
  THEN 1=1
  ELSE bar = '%'
END
2
  • 3
    Something like where(bar = ? or ? is null)? Commented Jun 16, 2022 at 18:31
  • 1
    questionning my whole career now ... Thanks anyway ! Commented Jun 16, 2022 at 19:37

1 Answer 1

3

you can try something like:

SELECT *
FROM foo 
WHERE COALESCE(bar, '') = COALESCE(?, bar, '')

so, if argument is null - column will be compared with itself, which is almost always returns true, except weird logic around null values, this is why we need coalesce on both sides of equation

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

3 Comments

Geez I must say. Thanks it works !
Maybe I should open a new question, in which case I will, but can this be adapted if multiple values in the list are selected (kind on IN ('p1', 'p2') ?
@HeyStackExchange yeah, sure like IN (coalesce(a,b,c...), coalesce(d,e,f...))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.