Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a value exists in another table within the SELECT clause

Tags:

sql

postgresql

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.

like image 663
Aayush Karki Avatar asked Jun 27 '17 06:06

Aayush Karki


People also ask

How do you check if a value is present in another table in SQL?

How do you check if a table contains any data in SQL? Using EXISTS clause in the IF statement to check the existence of a record. Using EXISTS clause in the CASE statement to check the existence of a record. Using EXISTS clause in the WHERE clause to check the existence of a record.

How do you check if a value from one table exists in another table?

Example using VLOOKUP You can check if the values in column A exist in column B using VLOOKUP. Select cell C2 by clicking on it. Insert the formula in “=IF(ISERROR(VLOOKUP(A2,$B$2:$B$1001,1,FALSE)),FALSE,TRUE)” the formula bar.

How do you check if a value exists in a table?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

Can we use exists in SELECT statement?

The exists operator can be used with either of these statements- SELECT, UPDATE, INSERT or DELETE.


1 Answers

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
like image 89
fthiella Avatar answered Oct 22 '22 01:10

fthiella