How to use SQL Select statement with IF EXISTS sub query?

Nalaka526 picture Nalaka526 · Oct 18, 2011 · Viewed 220.4k times · Source

How to select Boolean value from sub query with IF EXISTS statement (SQL Server)?

It should be something like :

SELECT 
  TABEL1.Id, 
  NewFiled = (IF EXISTS(SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID) 
                 SELECT 'TRUE' 
              ELSE 
                 SELECT 'FALSE') 
FROM TABEL1

Answer

ypercubeᵀᴹ picture ypercubeᵀᴹ · Oct 18, 2011

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID