Reputation: 841
I want to query names from table1 and also find if a name exists in table2. I have the following query but it doesn't seem to work. Any suggestions what I did wrong?
select A.name,
CASE WHEN A.name in (select B.name in table2 B)
THEN 'common'
ELSE 'not common'
END
from table1 A
Please note that I have to get "common" / "uncommon" from the select clause itself. I'm using postgres.
Upvotes: 20
Views: 80648
Reputation: 109
select a.name,
case
when a.name in (select distinct name from table2) then 'common'
else 'not common'
end as new
from table1 a
Upvotes: 0
Reputation: 679
Using subquery in SELECT CASE will cost more. Use left join instead like below
select A.name,
CASE WHEN B.name IS NOT NULL
THEN 'common'
ELSE 'not common'
END
from table1 A
left join table2 B
on A.name = B.name
Upvotes: 10
Reputation: 49089
I would use EXIST instead of IN:
select
A.name,
CASE
WHEN EXISTS (select *
from table2 B
where B.name = A.name)
THEN 'common'
ELSE 'not common'
END
from
table1 A
Upvotes: 26