How to use an IN clause with multiple columns on the same data in postgresql?

I have a query like this:

SELECT c1 from t WHERE c2 IN list1 AND c3 IN list1;

I want to combine this query to get something like this:

SELECT c1 from t WHERE c2 AND c3 IN list1;
+4
source share
2 answers

You can use arrays and the operator <@(contained) , for example:

with my_table(name1, name2) as (
values ('Emily', 'Bob'), ('Ben', 'Jack'), ('Emily', 'James')
)

select *
from my_table
where array[name1, name2] <@ array['Emily', 'Jack', 'James', 'Chloe'];

 name1 | name2 
-------+-------
 Emily | James
(1 row)

See also: How to use the same list twice in a WHERE clause?

+7
source

Suppose one Person table has Code and Email columns, so you can join this table with the list you want to iterate over.

*
P
(
('0000000264', 'luiza@gmail.com'), ('0000000262', 'ricardo@gmail.com')
)
L (, )
cod = P.code AND mail = P.email

-1

Source: https://habr.com/ru/post/1672348/


All Articles