Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

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;
like image 227
mohammad Avatar asked Mar 15 '17 12:03

mohammad


Video Answer


1 Answers

You can use arrays and the operator <@ (is contained by), e.g.:

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 same list twice in WHERE clause?

like image 133
klin Avatar answered Sep 29 '22 23:09

klin