Simple CASE Usage

caseoracle

Given:

TABLE test

x  y
a  1
b  2

TABLE test3

x  y
a  1
b  3

I wrote a query to retrieve all values from test, choosing the row with the higher y value.

select t1.x,
  CASE WHEN (EXISTS (select 1 from test2 t2 where t2.y > t1.y))
        THEN t2.y
       ELSE t1.y
  END as x
  from test t1
  LEFT JOIN test2 t2 ON t1.x=t2.x

output:

x  y
a  1
b  3

This query seems correct to me, but I'm not convinced.

Is this the right way to achieve what I'm trying to do?

Best Answer

Your query does have an error. The sub-query you are using for the EXIST is will always return true (or almost always), since you aren't lining it up on the "x" value.

As a side benefit, since it's not doing a sub-query it should perform faster as well.

Try this one:

 SELECT t1.x
    , CASE WHEN t2.y > t1.y THEN t2.y
            ELSE t1.y
            END AS y
 FROM test AS t1
    LEFT OUTER JOIN test2 AS t2 ON t2.x = t1.x