I have a Spring boot app with custom queries.
I need to find all database rows according to condition – if :myFlag
is true
, field in database must be in a list (:values
here), or null
.
Can I use something like this:
select *
from test
where id<4
and (case
when :myFlag then val in (:values)
else val in (:values) or val is null
end)
For example, if I have rows
id | val
1 | 1
2 | null
3 | 3
- When my
values = [1,3]
,myFlag = true
, then the query must return rows withid=1,3
. - If
myFlag = false
, then I need to retrieve rows withid=1,2,3
.
3
Answers
You don’t need a case here,
You can do:
See running example at db<>fiddle.
Yes, you can do pretty much exactly what you did, as long as you stick to the logic added in your later edit. Demo at db<>fiddle:
This:
means this:
Meanwhile, these express a somewhat different logic:
meaning this:
In the first paragraph, you do want the row
{id:2,val:null}
when:myFlag
istrue
. The example you added later showed the opposite logic.Funnily enough, @JGH’s code you went with, expresses yet another variant: