Home > other >  How to use the IN clause for multiple columns
How to use the IN clause for multiple columns

Time:09-02

I am using Postgres and I would like to put together the following sql queries

select * from t1 where type=57 and idt=2001 and date=1;
select * from t1 where type=59 and idt=2001 and date=1;
select * from t1 where type=57 and idt=2002 and date=3;
select * from t1 where type=57 and idt=2001 and date=2;
select * from t1 where type=59 and idt=2002 and date=1;

together in only one statement, like this:

select * from t1 where (type, idt, date) in 
{
(57, 2001, 1),
(59, 2001, 1),
(57, 2002, 3),
(57, 2001, 2),
(59, 2002, 1),
}

but I get the syntax error.

What's the correct syntax to achieve it?

CodePudding user response:

Where did you find, that curly braces would be correct in this case? Just use regular parentheses:

select * 
from t1 
where (type, idt, date) in (
                             (57, 2001, 1),
                             (59, 2001, 1),
                             (57, 2002, 3),
                             (57, 2001, 2),
                             (59, 2002, 1)
                           ) 

CodePudding user response:

You can join a table created with values clause, ie:

select t1.* from t1 inner join 
(values (57, 2001, 1),
(59, 2001, 1),
(57, 2002, 3),
(57, 2001, 2),
(59, 2002, 1)) as foo(type, idt, date)
on t1.type = foo.type and t1.idt = foo.idt and t1.date = foo.date;

DBFiddle demo

  • Related