DB2 Case When Exists

8.3k Views Asked by At

Searching a table to see if it contains X if it doesn't find X I need it to return Y. This is what I have tried so far:

SELECT WHEN T1.X IS NULL THEN Y ELSE T1.X END AS XY 
FROM TABLE1 T1
LEFT JOIN TABLE2 T2 ON T1.X = T2.X
WHERE T1.X IN (A, B, C);

SELECT CASE WHEN T1.X IS NOT NULL THEN T1.X ELSE Y END AS XY
FROM TABLE1 T1
WHERE T1.X IN (A, B, C)
AND T1.X IN (
    SELECT T2.X
    FROM TABLE2 T2);

SELECT CASE WHEN EXISTS (SELECT X FROM TABLE1) THEN X ELSE Y END AS XY
FROM TABLE1 
WHERE X IN (A, B, C);

I am getting 0 rows returned where it doesn't find A, B, or C, not Y. But if it finds A, B, or C it does properly return X.

3

There are 3 best solutions below

1
On BEST ANSWER

Simple UNION

SELECT X FROM TABLE1 WHERE X IN (A, B, C) 
UNION 
SELECT Y FROM SYSIBM.SYSDUMMY1 
WHERE NOT EXISTS (SELECT X FROM TABLE1 WHERE X IN (A, B, C))
0
On

This works as a record existence test in DB2

SELECT
  CASE COUNT(*)
    WHEN 0 THEN 'FALSE'
    ELSE 'TRUE'
  END as IsRecordThere
FROM MYTABLE 
WHERE COL1 = 'whatever' AND COL2 = 'etc'
0
On

I found this to work with DB2:

SELECT A, B, 
Case C
WHEN 'Citron' THEN 'Lemon'
WHEN 'Charlie' THEN 'Name'
end as Choice, 
D
FROM TABLE with UR;

Works with the DB2 java driver too.