AshesToAshes
AshesToAshes

Reputation: 967

Oracle SQL Case Statement in Where Clause

I'm new to Oacle SQL and I'm trying to get my head around what seems to be something easy...

Say I have a select like so:

select * from MRCONTRACT2
WHERE CASE 
        WHEN ("MR_CONTRACT2"."TERM_DATE" < sysdate)
            THEN 'Lapsed Contract'
        WHEN ("MR_CONTRACT2"."EFF_DATE" > sysdate)
            THEN 'Inactive Contract'
        ELSE 'Active Contract'
        END = 'Active Contract'

What does the where clause actually mean, as to me it does not make a full 'if' expression?

Upvotes: 0

Views: 6278

Answers (1)

Ben
Ben

Reputation: 52863

That query is equivalent to

select *
  from mrcontract2
 where term_date >= sysdate
   and eff_date <= sysdate

The CASE statement is evaluated in order, so if any "case" is true then every case after it is ignored. As you're checking whether the result of the case statement is the same as the ELSE clause then the statement is the same as the opposite of all other conditions.

I don't really like CASE statements in the WHERE clause but it can be useful as a way of simplifying logic; having a complex CASE statement that you want to evaluate against but don't want to translate.

Upvotes: 3

Related Questions