scottysseus
scottysseus

Reputation: 2010

IN clause for multiple columns on the same value set

I have a WHERE clause like below:

WHERE t1.col1 IN ('a', 'b', 'c') OR t2.col2 IN ('a', 'b', 'c');

I know that the two IN clauses will always have the same contents. Is there any way I can avoid duplicating them?

Something like:

WHERE (t1.col1 OR t2.col2) IN ('a', 'b', 'c')

Upvotes: 2

Views: 67

Answers (2)

Abelisto
Abelisto

Reputation: 15614

with flt(x) as (values('{a,b,c}'::text[]))
select
...
from ..., flt
where t1.col1 = any(flt.x) or t2.col2 = any(flt.x);

There are two ways to use some constant values in the PostgreSQL. Using CTE as shown above. Or using "options":

set foo.bar to '{a,b,c}';
select '{c,d,e}'::text[] && current_setting('foo.bar')::text[];

Upvotes: 1

user330315
user330315

Reputation:

You can use the array overlaps operator:

where array[t1.col1, t2.col2] && array['a','b','c']

Upvotes: 4

Related Questions